Reputation: 2881
Hey I have a model 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.
Upvotes: 9
Views: 5591
Reputation: 661
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
Upvotes: 17
Reputation: 41
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
Upvotes: 3
Reputation: 4113
I think you should write your own validation, because two different record of Foo has no idea about others related record (Bar)
Upvotes: 0