ruby on rails has_one association with unique
Asked Answered
F

3

9

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.

Fornax answered 7/6, 2011 at 16:48 Comment(0)
S
17

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
Second answered 7/6, 2011 at 17:33 Comment(2)
This would ensure that no two foos have the same bar, but @dhruvg is looking to ensure that no two bars belong to the same foo.Horsefly
As mentioned by @pynix-wang, validation of uniqueness does not guaranty anything in concurrent environments. You should use unique indexModestia
M
3

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

Malena answered 12/6, 2018 at 15:58 Comment(2)
validates_uniqueness_of may not uniq in a concurrency environment.Malena
you might also need to create a unique index and/or a foreign key constraint on the supplier column for the accounts table.From Rails GuideMalena
T
0

I think you should write your own validation, because two different record of Foo has no idea about others related record (Bar)

Tradition answered 7/6, 2011 at 16:57 Comment(1)
Irrelevent. That would be of concern if he wanted no two Foo's to have the same Bar. But that's not what he asked.Airspace

© 2022 - 2024 — McMap. All rights reserved.