问题
Running the following code to add an association enters multiple entries each time the code is ran:
store.categories << category
Is there a way to make it only enter unique associations between the two models in the db?
回答1:
Directly from the rails guides, hope it helps:
class Person
has_many :readings
has_many :posts, :through => :readings, :uniq => true
end
回答2:
Ignoring duplicates only seem to work with begin and rescue logic:
begin
stores.categories << category
rescue
puts "Duplicate entry ignored"
end
来源:https://stackoverflow.com/questions/8032342/how-to-enter-unique-associations-only