2015-09-07 74 views
0

我一直用這個嵌套的屬性與的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,那麼有沒有什麼辦法可以避免這種創建兩次在標籤?

回答

0

如果您希望它在數據庫中被禁止,您可以在check_tag表上的兩列的組合上創建唯一索引。如果你想在rails中處理它,你可以在Check模型上使用before_save回調來完成它(如果這是你創建這些模型的唯一方法),但這可能會讓你容易受到競爭條件的影響。

看到這個問題: Index on multiple columns in RoR