-1

I have the following associations:

Restaurant has_many Menus 
Menu belongs_to Restaurant
Restaurant belongs_to City 
City has_many Restaurants

When doing the following query:

Menu.includes(:restaurant).where("restaurants.city_id", 3) I get the following error:

ActiveRecord::StatementInvalid: PG::Error: ERROR:  argument of WHERE must be type boolean, not type integer

What am I doing wrong here?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

1

That's not the correct syntax for .where. You want .where("restaurants.city_id = ?", 3)

MrTheWalrus
  • 9,670
  • 2
  • 42
  • 66
  • I took it from the Rails guide directly, where you can find "Post.includes(:comments).where("comments.visible", true)" - http://guides.rubyonrails.org/active_record_querying.html (section 12.2) – Hommer Smith May 07 '13 at 17:33
  • That seems to work entirely by accident - if the conditions are a boolean, PostGres knows how to treat it as a condition (the query run is `SELECT "comments".* FROM "comments" WHERE (visible)`. It's the same query as if you run `.where('comments.visible', false)`, which is definitely _not_ what you would expect that to do. – MrTheWalrus May 07 '13 at 17:38
  • I should also point out that that same guide, when discussing conditions on eager loaded tables, says "Don't". Which I agree with - if you want to use conditions on an association, join the association _and_ include it. – MrTheWalrus May 07 '13 at 17:41
  • MrTheWalrus why is it bad to use a condition on includes though? I want to eager load the restaurants and do a where because I just want restaurants from a particular city... How would I do that without includes? – Hommer Smith May 07 '13 at 17:49
  • This question is a pretty good write-up of issues with conditions in eager loads: http://stackoverflow.com/questions/4197418/rails-3-eager-loading-with-conditions – MrTheWalrus May 07 '13 at 18:30