避免重复录入,通过轨道
问题描述:
我一直用这个嵌套的属性与的has_many:通过避免重复录入,通过轨道
class Check < ActiveRecord::Base
has_many :checks_tags, dependent: :destroy
has_many :tags, through: :checks_tags
attr_accessible :tags_attributes, :checks_tags_attributes
accepts_nested_attributes_for :tags, :checks_tags
end
class Tag < ActiveRecord::Base
has_many :checks_tags, dependent: :destroy
has_many :checks, through: :checks_tags
end
class CheckTag < ActiveRecord::Base
belongs_to :check
belongs_to :tag
end
所以这里的问题是,当我用这个哈希创建
"tags_attributes"=>[{"id"=>"", "name"=>"test12", "company_id"=>"1"}, {"id"=>"", "name"=>"test12", "company_id"=>"1"}]
其实这里有两个标签同名,所以它创建标签两次,并将两次后CheckTag,那么有没有什么办法可以避免这种创建两次在标签?
答
如果您希望它在数据库中被禁止,您可以在check_tag
表上的两列的组合上创建唯一索引。如果你想在rails中处理它,你可以在Check
模型上使用before_save回调来完成它(如果这是你创建这些模型的唯一方法),但这可能会让你容易受到竞争条件的影响。
看到这个问题: Index on multiple columns in RoR