RoR: How do I ensure that my object is bound to only one object?

In my Ruby on Rails application, I have a User table and a Foo table. I also have a User_Foo table that stores cross reference data.

I have everything to do with my views to work the way I want, however now I need to make sure that the same Foo doesn't get my user more than once.

What's the best way to do this?

I assumed I could use validates_uniqueness_of in my model, but that doesn't apply to a single user. Do I need to do this when updating? I was hoping to create a built-in "Ruby Way" for this.

+1


source to share


1 answer


validates_uniqueness_of covers it, you just need to add an extra parameter to get the desired behavior.

Assuming you have a UserFoo model for storing cross-references (and they don't modelless it). The following check will prevent duplicate references to foo-user.



class UserFoo < ActiveRecord::Base
  belongs_to :user
  belongs_to :foo
  validates_uniqueness_of :foo_id, :scope => :user_id

      

+7


source







All Articles