在Ruby on Rails中具有的嵌套属性具有一种关联

时间:2018-07-18 23:21:10

标签: ruby-on-rails has-one accepts-nested-attributes

今天,我试图用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>

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

谢谢。


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

1 个答案:

答案 0 :(得分:1)

逐步建立此关联的指南。
在地址迁移文件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

上关注本教程