Reputation:
Let say I have 3 tables:
schools{id, name, desc, adress}
reviews{id, content, rating, school_id, user_id} # user_id & schoold_id is foregin keys
users{id, name, city}
How do I write a rails scope or method the joins all 3 tables and grab the column
the schools.name
, reviews.content
and reviews.rating
, the users.name
I tried somehting this, but it only return the review data and not the joining part.
Review.joins(:school, :user).select("content, rating, schools.name, users.name").all
I am using rails 3.2
Upvotes: 1
Views: 262
Reputation: 2235
You just need to define has-many :through relationships for schools and users like this:
class School < ActiveRecord::Base
has_many :users, :through => :reviews
end
class Review < ActiveRecord::Base
belongs_to :users
belongs_to :schools
end
class User < ActiveRecord::Base
has_many schools, :through => reviews
end
In your Review controller you can do
def index
@reviews = Review.all
end
Then in your views each review object will have a school and a user associated with it, so you would just do:
review.content, review.rating, review.user.name, review.school.name
Reading this will help you understand why: http://guides.rubyonrails.org/association_basics.html
Upvotes: 1