deruse
deruse

Reputation: 2881

ruby on rails has_one association with unique

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

Answers (3)

Blizzo
Blizzo

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

Pynix Wang
Pynix Wang

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

bor1s
bor1s

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

Related Questions