Doing JOINs the Rails way
April 18, 2008 1:37 PM Subscribe
How can I do a Rails
JOIN without SQL, using the two tables' existing
posted by Blazecock Pileon to computers & internet (5 answers total) 5 users marked this as a favorite
I have two classes
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
Therefore, I'd like to search on
samples_users to find a previously-entered record which matches those two
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