Search code examples
mysqlruby-on-railshas-manybelongs-to

Rails mysql: How to query tables with deeply nested relations(has_many and belongs_to)?


I have the following models:

class User < ActiveRecord::Base
  has_many :keys
end

class Key < ActiveRecord::Base
  belongs_to :room
end

class Room < ActiveRecord::Base
  belongs_to :building
end

class Building < ActiveRecord::Base
  #Has column "name"
end

I want to get all users that have keys that belong to a building with the name "HQ"

Bassicaly something like this(pseudo query):

Users = users.where('keys.room.building.name=?', name)

This is the furthest I got:

users = User.joins(:keys).where('keys.room.building.name=?', name)

But it gives the following error:

ActionView::Template::Error (Mysql2::Error: You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near '.name='HQ')' at line 1: 
SELECT `users`.* FROM `users` INNER JOIN `keys` ON `keys`.`user_id` = `users`.`id` WHERE (keys.room.building.name='HQ')):

Solution

  • Give this a shot

    User.joins(keys: [room: :building]).where("buildings.name" => name)