【发布时间】:2021-07-17 08:52:28
【问题描述】:
我正在尝试用通常的方式处理嵌套属性:
型号:
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。
提前致谢
【问题讨论】:
标签: ruby-on-rails