我想通过外键同步has_many关联。看来我必须编写自定义代码才能做到这一点。是否有Rails / Active Record魔术/宝石来实现这一目标?具体来说,我想同步一个联接表,其中外键对应该是唯一的。
class Food < ActiveRecord::Base
has_many :food_tags, :dependent=>:destroy, :inverse_of => :food
accepts_nested_attributes_for :food_tags, :allow_destroy => true
end
class FoodTag < ActiveRecord::Base
belongs_to :tag, :inverse_of=>:food_tags
belongs_to :food, :inverse_of=>:food_tags
end
class Tag < ActiveRecord::Base
has_many :food_tags, :dependent=>:destroy, :inverse_of=>:tag
has_many :foods, :through=>:food_tags
end
对于具有嵌套属性(或JSON API)的表单,我真的想省略FoodTag ID,并在更新食物时使用tag_id进行同步。
我想在更新时提交,以显示标签已设置或清除
# this one is set
food[food_tag_attributes][0][tag_id] = 2114
food[food_tag_attributes][0][_destroy] = false
# this one is cleared
food[food_tag_attributes][1][tag_id] = 2116
food[food_tag_attributes][1][_destroy] = true
相反,我必须将此提交更新:
# this one is set
food[food_tag_attributes][0][id] = 109293
food[food_tag_attributes][0][tag_id] = 2114
food[food_tag_attributes][0][_destroy] = false
# this one is cleared
food[food_tag_attributes][0][id] = 109294
food[food_tag_attributes][1][tag_id] = 2116
food[food_tag_attributes][1][_destroy] = true
这给客户增加了负担,要求他们知道食物标签记录的ID,而不是仅仅能够基于标签ID来设置或清除标签。
能容易做到吗?我确定我可以在Food上编写一个before_save过滤器,但是似乎应该有一个合理的通用解决方案。
最佳答案
视图帮助器中有一个名为index:的fields_for选项。您可以将索引设置为您的foreign_key。然后,您的foreign_key将被用作引用您的对象的键,而不是连续的或一些任意的数字。
编辑:<%= form_for @person do |person_form| %> <%= person_form.text_field :name %> <% @person.addresses.each do |address| %> <%= person_form.fields_for address, **index**: address.id do |address_form|%> <%= address_form.text_field :city %> <% end %> <% end %> <% end %>