Doing JOINs the Rails way
April 18, 2008 1:37 PM Subscribe
How can I do a Rails
find JOIN without SQL, using the two tables' existing
has_and_belongs_to_many relationships?
I have two classes Sample and User, which have:
has_and_belongs_to_many :users, :uniq => true
has_and_belongs_to_many :samples, :uniq => true
relationships in their respective model files. This sets up the many-to-many relationship between the two classes.
Let's say I want to associate a Sample instance with a User instance:
Sample.find_by_id(params[:sample][:id]).users << User.find_by_id(params[:user_id])
So far so good.
But I'd like to avoid duplicates of a combination of sample_id and user_id.
Therefore, I'd like to search on samples_users to find a previously-entered record which matches those two id numbers.
I could do this with a SQL JOIN but I'd like to learn the Rails way, so that I don't have to write custom SQL that will likely break during development.
How to I use the find method on Sample to get any matches with a specified sample_id and user_id?>
posted by Blazecock Pileon to computers & internet (5 answers total) 5 users marked this as a favorite
add_index :samples_users, [:sample_id, :user_id], :unique => true
There's a chance you'll need a begin / rescue for saving - I'm not sure if it just returns false when things don't work out or if AR throws an exception.
posted by soma lkzx at 2:03 PM on April 18, 2008