views:

102

answers:

1

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

I have everything wired up for my views to work as I want, however, now I need to make sure that the same Foo doesn't get assigned to my User more than once.

What's the best way to do this?

I assumed that I could use validates_uniqueness_of in my model, but that wouldn't be specific to a single User. Do I need to do this on the update? I was hoping to have a built in "Ruby Way" of doing this.

+7  A: 

validates_uniqueness_of covers it, you just need to add an extra option to get the behaviour you want.

Assuming you have a UserFoo model to store the cross reference relationship (and aren't doing it modelless). The following validation won't allow duplicate foo-user links.

class UserFoo < ActiveRecord::Base
  belongs_to :user
  belongs_to :foo
  validates_uniqueness_of :foo_id, :scope => :user_id
Michael
awesome. that's exactly what i was looking for.
levi rosol