Melvin Ch'ng Melvin Ch'ng - 2 years ago 93
SQL Question

How to manually join two different table with different attribute name in Ruby on Rails controller

I am currently making a website that runs on Ruby on Rails. I am facing some issues while I was trying to join two tables, Rates and Locations, that I have with two different attributes name.


id rater_id rateable_id
(and a few more attributes in this table)

id title body user_id
(and a few more attributes in this table)

Here is the query that I am trying to do in SQL.

FROM rates, locations
WHERE rates.rater_id = locations.user_id AND rates.rateable_id =

I have read the official active record documents that provided by I have tried doing these, but it does not work. Here is the code that I am trying to implant in

@join_rating = Rate.joins(:locations).where("rates.rateable_id = AND rates.rater_id =")
@all_rating = @all_rating.where(rater_id: @user)
@count_all_rating = @all_rating.count

, is trying to join the attributes with different names.

, is trying to filter which location to show using the user ID

, is trying to calculate the total numbers of locations that are rated by the user

Assume that everything is setup correctly and the only error is in the query that I am trying to do, how should I rewrite the statement so that I am able to show the locations that the user has rated using

Thank you!

Answer Source

A few points:

When in ActiveRecord you're starting a statement with the Rate class, it means the result is going to be a collection of Rate objects. So if you're trying to show locations, you should start with a Location class.

@locations_user_rated = Location.joins('INNER JOIN rates').where('rates.rater_id' =>"rates.rateable_id = AND rates.rater_id =")

By the way, note that there is difference between Location.joins('INNER JOIN rates') and Location.joins(:rates). When you provide a string, Active Record will use it as-is. When you provide a symbol, ActiveRecord will look for the association called has_many :rates or has_and_belongs_to_many :rates and use the foreign key definition of the association to know how to perform the where clause appropriately. This is very convenient typically, but note that you are deviating from the Rails default conventions, so to make it work you'll need to set the associations correctly.

You can find more about how to customize associations here, and BenanaNeil's answer below is nicely pursuing this direction.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download