How to enter unique associations only?

大憨熊 提交于 2019-12-21 09:23:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!