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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With