Rails使用现有记录嵌套属性



我正试图用通常的方法处理嵌套属性:

型号:

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与之关联。我现在不知道在Locationname存在的情况下如何重建InventoryItemLocation之间的关联。控制器中的:@inventory_item.build_location一直在创建一个新的Location

提前感谢

accepts_nested_attributes_for :locationInventoryItem模型添加了一个方法: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