嵌套属性在 Ruby 和 Rails 中有一个关联

Nested attributes with has one association in Ruby on Rails

今天我试图用 HouseAddress 写一个嵌套表单。

# 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>

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

谢谢。


当我转回代码时,我添加了 <%= 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

建立这个协会的分步指南。
在地址迁移文件中添加对房屋的引用 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 添加到 HousesController new 方法

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

接受地址参数,

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

您的代码的其他部分是正确的,包括模型。 在 railscasts

上按照本教程进行操作