我有以下型号:
class Property < ApplicationRecord
# Other validations
has_one :address
accepts_nested_attributes_for :address, update_only: true
end
class Address < ApplicationRecord
has_one :country
has_one :state
has_one :city
has_one :suburb
belongs_to :property
end
country
、state
和的关系都通过 acity
和相互关联。suburb
has_many
belongs_to
问题是 :
在我的properties/_form.html.erb
文件中,我尝试使用嵌套fields_for
的:address
和在那些嵌套字段上创建地址options_from_collection_for_select
。下面的代码:
<fieldset>
<div class="form-group">
<%= form.label :address, "Dirección", class: "col-sm-2 control-label"%>
<div class="col-sm-9">
<%= form.fields_for :address do |ff| %>
<div class="row">
<div class="col-sm-4">
<select class="form-control" name="property[address_attributes][country_id]" >
<%= options_from_collection_for_select(Country.all, :id, :name) %>
</select>
</div>
<div class="col-sm-4">
<select class="form-control" name="property[address_attributes][state_id]" >
<%= options_from_collection_for_select(State.all, :id, :name) %>
</select>
</div>
<div class="col-sm-4">
<select class="form-control" name="property[address_attributes][city_id]" >
<%= options_from_collection_for_select(City.all, :id, :name) %>
</select>
并在提交时收到此错误:
更新 1
所以我用这个改变了我的表格:
<%= ff.select :country, options_from_collection_for_select(Country.all, :id, :name) %>
在我所有的关系上,现在我得到的错误是:
Country(#70194352893700) expected, got "1" which is an instance of String(#70194311847460)
更新 2:
这是我schema.rb
描述我的addresses
表的代码:
create_table "addresses", force: :cascade do |t|
t.string "street"
t.integer "number"
t.integer "zip_code"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "property_id"
t.integer "countries_id"
t.integer "states_id"
t.integer "cities_id"
t.integer "suburbs_id"
t.index ["cities_id"], name: "index_addresses_on_cities_id"
t.index ["countries_id"], name: "index_addresses_on_countries_id"
t.index ["property_id"], name: "index_addresses_on_property_id"
t.index ["states_id"], name: "index_addresses_on_states_id"
t.index ["suburbs_id"], name: "index_addresses_on_suburbs_id"
end