今天我试图用House
and编写一个嵌套表单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