I am getting missing FROM clause error (shown below)
I want to find the entries whose associated reports’ city is the same as the users’ city, thus only showing relavant entries to users. So, if a user belongs to a city that a report does, the user should be shown the entries from that report.
I tried a few things, one being this scope in the Entry model:
scope :report_in_city, lambda { |user| joins(:report).where("report.city_id = ?", user.city_id) }
And if I call Entry.report_in_city(user)
I get this error:
SELECT "entries".* FROM "entries" INNER JOIN "reports" ON "reports"."id" = "entries"."report_id" WHERE (report.city_id = 1)
ActiveRecord::StatementInvalid: PG::Error: ERROR: missing FROM-clause entry for table "report"
LINE 1: ... ON "reports"."id" = "entries"."report_id" WHERE (report.cit...
^
: SELECT "entries".* FROM "entries" INNER JOIN "reports" ON "reports"."id" = "entries"."report_id" WHERE (report.city_id = 1)
I have a few models set up like this:
class Report
belongs_to user
belongs_to city
has_many entries
class Entry
belongs_to report
class User
has_many reports
belongs_to city
class City
has_many users
has_many reports
I am new to sql and would appreciate any advice on this query!
Since that string condition
"report.city_id = ?"goes into the SQL, you have to use the table names. Rails is cute about going back and forth between plural and singular, but SQL only knows the table namereports. You can see that in the generated SQL likeON "reports"."id" = "entries"."report_id". The table name is plural.Try this:
or the Rails way: