Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 675
deruse Avatar asked Jun 07 '11 16:06

deruse


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


2 Answers

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
like image 155
Blizzo Avatar answered Sep 21 '22 04:09

Blizzo


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

like image 35
Pynix Wang Avatar answered Sep 21 '22 04:09

Pynix Wang