如何在Rails 5中获得一个有作用域的父项的子项记录
问题描述:
我需要一个控制器来传递符合特定范围的父项的子项记录。我希望这个范围在父记录上。如何在Rails 5中获得一个有作用域的父项的子项记录
class Parent < ApplicationRecord
has_many :children
scope :not_blue, -> { where(blue:false) }
scope :blue, -> { where(blue:true) }
# Subjective, may change in the future
scope :funny, -> { where('funny_scale>=?',5) }
scope :genies, -> { blue.funny }
end
class Child < ApplicationRecord
belongs_to :parent, required: true
end
class ChildrenController < ApplicationController
def index
# Yeah, this breaks horribly (and should), but you get my gist
@children_of_genies = Parent.genies.children
end
end
我知道答案可能是盯着我脸上,但谷歌搜索的正确组合正在逃避我。
答
如果您想您的解决方案仍然是一个ActiveRecord::Associations::CollectionProxy
尝试Children.where(parent_id: Parent.genies.ids)
你那么可以把进入范围。
scope: children_of_genies, -> { where(parent_id: Parent.genies.ids)
答
作用域返回ActiveRecord_Relation
,得到children
为它的每个成员可以使用collect
:
@children_of_genies = Parent.genies.collect { |p| p.children }
谢谢!这正是我想要的。 – jfr