0

今天我试图用Houseand编写一个嵌套表单Address

# app/models/house.rb
class House < ApplicationRecord
  has_one :address

  accepts_nested_attributes_for :address
end

# app/models/address.rb
class Address < ApplicationRecord
  belongs_to :house
end

这是schema.rb

# db/schema.rb
create_table "addresses", force: :cascade do |t|
  t.string "state", null: false
  # ...
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "houses", force: :cascade do |t|
  t.integer "rent", null: false
  # ...
  t.bigint "address_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["address_id"], name: "index_houses_on_address_id"
end

add_foreign_key "houses", "addresses"

这就是我正在尝试的

<div class="col-md-6 mx-auto">
  <%= form_for @house do |form| %>
    <div class="form-row">
      <div class="form-group col-6">
        <%= form.label :rent %>
        <%= form.text_field :rent, class: "form-control" %>
      </div>
    </div>
    <%= form.fields_for :address do |address_form| %>
      <div class="form-row">
        <div class="form-group col-4">
          <%= address_form.label :state %>
          <%= address_form.text_field :state %>
        </div>
      </div>
    <% end %>
    <%= form.submit "Submit", class: "btn btn-primary" %>
  <% end %>
</div>

我正在尝试编写一个具有地址字段的表单;但是,当我运行这段代码时,它不会返回表单。任何关于嵌套形式的提示都会很棒!

谢谢你。


当我回到代码时,我添加了<%= form.fields_for :addresses do |address| %>. 这是好的做法吗?


class HousesController < ApplicationController
  #...
  def new
    @house = House.new
  end

  def create
    @house = House.new house_params
    @house.user = current_user

    if @house.save
      redirect_to root_path
    else
      render :new
    end
  end
  # ...
end
4

1 回答 1

3

逐步指导建立此关联。
在地址迁移文件中添加对房屋的引用t.belongs_to :house, index: true

class CreateAddressses < ActiveRecord::Migration[5.2]
  def change
    create_table :addressses do |t|
      t.belongs_to :house, index: true
      t.string :state
      t.timestamps
    end
  end
end

添加@house.build_address到 HousesControllernew方法

def new
  @house = House.new
  @house.build_address
end

接受地址参数,

def house_params
  params.require(:house).permit(:name, address_attributes: [:state])
end

您的代码的其他部分是正确的,包括模型。按照这个关于railscasts的教程

于 2018-07-19T02:39:23.460 回答