[英]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" 我想获取所有具有属于“ HQ”名称的建筑物的钥匙的用户
Bassicaly something like this(pseudo query): 像这样的basicaly(伪查询):
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')):
试一下
User.joins(keys: [room: :building]).where("buildings.name" => name)
Try this:- 尝试这个:-
User.joins(:keys => {:room => {:building}}).where("buildings.name" => name)
Assuming you also want to eager load avoid 1+N queries: 假设您还希望避免加载1 + N个查询:
User.includes(:keys => {:room => {:building}}).where("buildings.name" => name)
Hope this is useful to you!! 希望这对您有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.