【发布时间】:2021-07-16 11:46:58
【问题描述】:
我有一个嵌套属性:
class InventoryItem < ApplicationRecord
belongs_to :location
accepts_nested_attributes_for :location
end
class Location < ApplicationRecord
has_many :inventory_items
has_many :bins
accepts_nested_attributes_for :bins
end
class Bin < ApplicationRecord
belongs_to :location
end
inventory_item 表单:
<%= form.fields_for :location do |location| %>
<div class="field">
<%= location.label :location_name %>
<%= location.text_field :name %>
</div>
<%= location.fields_for :bins do |bin| %>
<div class="field">
<%= bin.label :bin_name %>
<%= bin.text_field :name %>
</div>
<% end %>
</div>
<% end %>
在inventory_item 控制器中:
def new
@inventory_item = InventoryItem.new
@inventory_item.build_location.bins.build
end
def inventory_item_params
params.require(:inventory_item).permit(:location_id, location_attributes:[:name, bins_attributes:[:name]])
end
形式:
我的问题是我可以创建一个Location 和Bin 名称为空白的InventoryItem,它会创建一个新的Location 和Bin 以及InventoryItem 和空白@987654334 之间的相应关联@。
我希望当Location 名称或Bin 名称在表单中为空白时,新的Location、新的Bin 将不创建关联。
提前致谢
【问题讨论】:
标签: ruby-on-rails ruby