我发现自己处于以下半正常状态:
class Contract
has_many :contract_locations, dependent: :destroy
has_many :locations, through: :contract_locations
end
class ContractLocation
enum role: { shipper: 0, receiver: 1 }
belongs_to :contract
belongs_to :location
end
class Location
has_many :contract_locations, dependent: :destroy
has_many :contracts, through: :contract_locations
end
有问题的形式是Contract
形式,在这种情况下工作正常,对于每个相关位置,我选择一个位置和一个角色。在建筑方面,这是有效的,但因为我实际上有两个Location
“类型”(:shipper
和:receiver
),我想把它们作为形式的两个独立部分。所以基本上是表单的一部分,它有自己的“添加送货地点”按钮,另一部分有自己的“添加接收位置”按钮。我能够实现这一点,但它导致的问题是从现有关系填充表单时。如果我提交这样的表格:
然后我再次加载编辑表单,值填充如下:
很明显,这是因为茧正在填充相关的Location
s,因为它应该,并没有区分Location
s与特定的role
s。是否有任何作用域功能允许我只为某些特定范围(如Location
)为role: :shipper
s创建这些表单元素?
编辑:我应该注意,我已经尝试使用提供的Javascript回调,特别是before-insert
,但它看起来不像他们第一次加载窗体时触发。
我已经解决了我的问题,虽然我仍然有兴趣看看Cocoon是否有内置的方法来解决这个问题。
我的解决方案是检查我的cocoon partial中的表单对象:
<%= f.simple_fields_for :contract_locations do |contract_location| %>
<!-- This check prevents locations of the wrong role being rendered in the wrong form section. -->
<% if contract_location.object.role == role.to_s %>
<%= render 'form_location_fields', f: contract_location, role: role %>
<% end %>
<% end %>