my current user.rb模型
class User < ApplicationRecord
has_many :children,
-> (user) { unscope(:where).where("father_id = :id OR mother_id = :id", id: user.id) },
class_name: "User"
has_many :grandchildren,
-> (user) { unscope(:where).where("father_id IN (:ids) OR mother_id IN (:ids)", ids: user.children.ids) },
class_name: "User"
belongs_to :mother, class_name: "User", optional: true
belongs_to :father, class_name: "User", optional: true
end
我的当前数据(空数据为零):
所有查询现在都可以工作了:
但是对于 .grandchildren
查询,您可以看到在控制台中,创建了三个独立的查询。有没有办法只生成一个查询?
我在尝试示例方法,因为我可以输入原始sql,但似乎无法理解它。例如:
def children
sql = ("SELECT users.* FROM users WHERE (father_id = id OR mother_id = id)")
p ActiveRecord::Base.connection.execute(sql)
end
1条答案
按热度按时间n3ipq98p1#
你可以替换
具有