Hey I have a mode开发者_开发问答l foo that has_one :bar
. And bar belongs_to :foo
. I was wondering if there is a way to augment the has_one such that no two bars can belong to the same foo. I looked at the documentation for has_one and it seems like there is no :uniq parameter which I am allowed to specify. So do I have to create a custom validation to achieve this? Or is there an easier way?
Thanks.
You do not need a custom validation, just enforce uniqueness of bar for any given foo
class Bar < ActiveRecord::Base
belongs_to :foo
validates_uniqueness_of :foo_id
end
add a uniq index to foo_id in table bars so you can not create 2 bars with same foo_id, so only one bar can belongs to foo
I think you should write your own validation, because two different record of Foo has no idea about others related record (Bar)
精彩评论