我正试图用通常的方法处理嵌套属性:
型号:
class InventoryItem < ApplicationRecord
belongs_to :location
accepts_nested_attributes_for :location
end
形式:
<div class="field">
<%= form.fields_for :location do |location| %>
<%= location.label :location_name %>
<%= location.text_field :name %>
<% end %>
</div>
控制器:
def new
@inventory_item = InventoryItem.new
@inventory_item.build_location
end
def inventory_item_params
params.require(:inventory_item).permit(:location_id, location_attributes:[:name])
end
我的问题是,我希望如果Location
存在,则新的InventoryItem
与之关联。我现在不知道在Location
和name
存在的情况下如何重建InventoryItem
和Location
之间的关联。控制器中的:@inventory_item.build_location
一直在创建一个新的Location
。
提前感谢
accepts_nested_attributes_for :location
为InventoryItem
模型添加了一个方法:location_attributes=
。
你对这个方法有一个特殊的约束,所以你需要在inventory_item.rb中覆盖它,比如这样:
#inventory_item.rb
def location_attributes=(attrs)
begin
self.location_id = Location.find_by!(name: attrs[:name])
rescue ActiveRecord::RecordNotFound
super
end
end