模型的范围关联以单一形式多次使用 simple_form 和 cocoon
Scope associations for a model used multiple times in a single form with simple_form and cocoon
我发现自己处于以下半正常状态:
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
表格,在这种情况下工作正常,对于每个关联的位置,我 select 一个位置和一个角色。从架构上讲,这是可行的,但因为我实际上有两个 Location
"types"(:shipper
和 :receiver
),所以我希望将它们作为表单的两个独立部分。所以本质上,表单的一部分有自己的 "add shipping location" 按钮,另一部分有自己的 "add receiving location" 按钮。我能够做到这一点,但它导致的问题是当表单是从现有关系中填充时。如果我这样提交表格:
然后我再次加载编辑表单,值是这样填写的:
很明显,这是因为 cocoon 只是按照预期填充关联的 Location
,并没有区分 Location
和特定的 role
。是否有任何范围界定功能允许我只为某些特定范围(如 role: :shipper
)的 Location
创建这些表单元素?
编辑:我应该注意到我已经尝试使用提供的 Javascript 回调,尤其是 before-insert
,但看起来它们并没有在第一次加载表单时触发.
我已经解决了我的问题,但我仍然想看看 Cocoon 是否有内置的方法来解决这个问题。
我的解决方案是检查我的 cocoon 部分中的表单对象:
<%= 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 %>
我发现自己处于以下半正常状态:
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
表格,在这种情况下工作正常,对于每个关联的位置,我 select 一个位置和一个角色。从架构上讲,这是可行的,但因为我实际上有两个 Location
"types"(:shipper
和 :receiver
),所以我希望将它们作为表单的两个独立部分。所以本质上,表单的一部分有自己的 "add shipping location" 按钮,另一部分有自己的 "add receiving location" 按钮。我能够做到这一点,但它导致的问题是当表单是从现有关系中填充时。如果我这样提交表格:
然后我再次加载编辑表单,值是这样填写的:
很明显,这是因为 cocoon 只是按照预期填充关联的 Location
,并没有区分 Location
和特定的 role
。是否有任何范围界定功能允许我只为某些特定范围(如 role: :shipper
)的 Location
创建这些表单元素?
编辑:我应该注意到我已经尝试使用提供的 Javascript 回调,尤其是 before-insert
,但看起来它们并没有在第一次加载表单时触发.
我已经解决了我的问题,但我仍然想看看 Cocoon 是否有内置的方法来解决这个问题。
我的解决方案是检查我的 cocoon 部分中的表单对象:
<%= 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 %>