GlyphGryph
GlyphGryph

Reputation: 4794

Why does a where clause on an association look at "object_id", and how do I write a where clause correctly?

I thought I was trying to do something simple, and am a bit confused as to why it's not working - basically, find all "Game" objects that contain a particular message (or no message).

$ Game.where(:message => Message.first)

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: games.game_id: SELECT "games".* FROM "games" WHERE "games"."game_id" = 1

$ Game.where(:message => nil)

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: games.game_id: SELECT "games".* FROM "games" WHERE "games"."game_id" = 1

$ Game.where(:message => nil).to_sql

 => "SELECT \"games\".* FROM \"games\" WHERE \"games\".\"game_id\" = 1" 

I don't really understand what's being returned to me here, though - why is it checking for a games.game_id attribute? How do I actually run a query to get Games with a specific message or no messages at all?

The Game object "has_one" a message, which "belongs_to" the game object. The relationships themselves work fine, I just can't figure out how to do the where clause.

Upvotes: 0

Views: 25

Answers (1)

Elena  Unanyan
Elena Unanyan

Reputation: 1209

It's normal! You can use this assotiations only reverse. You can try Message.where(game: nil), but if you will to get games, you mast use this:

Game.joins(:message).where(message: Message.first)

Upvotes: 2

Related Questions