我有一个循环依赖的模型:
class InventoryItem < ApplicationRecord
belongs_to :location
belongs_to :bin
accepts_nested_attributes_for :location
accepts_nested_attributes_for :bin
end
class Location < ApplicationRecord
has_many :bins
has_many :inventory_items
accepts_nested_attributes_for :bins
end
class Location < ApplicationRecord
has_many :bins
has_many :inventory_items
accepts_nested_attributes_for :bins
end
inventory item
形式:
<div class="field">
<%= form.fields_for :location do |location| %>
<%= location.label :location_name %>
<%= location.text_field :name %>
<% end %>
</div>
<div class="field">
<%= form.fields_for :bin do |bin| %>
<%= bin.label :bin_name %>
<%= bin.text_field :name %>
<% end %>
</div>
还有 inventory item
控制器:
def new
@inventory_item = InventoryItem.new
@inventory_item.build_bin
@inventory_item.build_location
end
def inventory_item_params
params.require(:inventory_item).permit(:location_id, :bin_id, location_attributes:[:name], bin_attributes:[:name])
end
但是当我提交表单时出现错误:
Bin location must exist
我不知道在哪里或如何创建 Bin
和 Location
之间的关系,或者是否可能。
提前致谢
答案 0 :(得分:2)
你没有循环依赖。
所以如果你按照正确的顺序创建它们
你应该没事。
像这样
# the nesting in params may be off but you can definitely figure this out by looking at the console log of form's request.
# 1. Create location with name (no dependencies)
location = Location.create({name: params[:location][:name]})
# 2. Create bin referencing location
bin = Bin.create({location: location, name: params[:bin][:name]})
# 3. Create inventory item referencing both.
@inventory_item = InventoryItem.create({bin: bin, location: location})
我不确定如何使用 accepts_nested_attributes_for
执行此操作,但如果您可以使其正常工作,那将是一个干净的解决方案。