我需要一个控制器来传递符合特定范围的父母的子记录。我希望这个范围在父记录上。
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
我知道答案可能正在盯着我,但谷歌搜索的正确组合让我望而却步。
答案 0 :(得分:0)
范围返回ActiveRecord_Relation
,为children
的每个成员获取collect
:
@children_of_genies = Parent.genies.collect { |p| p.children }
答案 1 :(得分:0)
如果您希望自己的解决方案仍然是ActiveRecord::Associations::CollectionProxy
尝试Children.where(parent_id: Parent.genies.ids)
,那么您可以将其转变为范围。
scope: children_of_genies, -> { where(parent_id: Parent.genies.ids)