Nested table querying with ActiveRecord
Sometimes you need to query a joined table in ActiveRecord. This can be easily done via the hash syntax:
User.where(greetings: {text: "HOWDY"}).to_sql
=> SELECT "users".* FROM "users" WHERE ("greetings"."text" = 'HOWDY')
Note: the key here (greetings
) is pluralized because we're referencing a table name and not a potential relationship that ActiveRecord knows about.
Note: I've ommited a join to the greetings
table that would have this query make sense
Cool: so we can do that but there's even an alternative way to handle this using dot notation
User.where("greetings.text": "HOWDY"}).to_sql
=> SELECT "users".* FROM "users" WHERE ("greetings"."text" = 'HOWDY')
Under the hood, ActiveRecord will convert dots from the string key and interpret them as table and column names.
Tweet