2017-10-12 25 views
0

我需要一个控制器来传递符合特定范围的父项的子项记录。我希望这个范围在父记录上。如何在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 

我知道答案可能是盯着我脸上,但谷歌搜索的正确组合正在逃避我。

回答

0

如果您想您的解决方案仍然是一个ActiveRecord::Associations::CollectionProxy尝试Children.where(parent_id: Parent.genies.ids)你那么可以把进入范围。

scope: children_of_genies, -> { where(parent_id: Parent.genies.ids)

+0

谢谢!这正是我想要的。 – jfr

0

作用域返回ActiveRecord_Relation,得到children为它的每个成员可以使用collect

@children_of_genies = Parent.genies.collect { |p| p.children }

+1

或'map':'@children_of_genies = Parent.genies.map(:儿童)' – fanta

+0

@fanta +1,我总是用收集时,我有,当我创建一个新的阵列和地图修改现有的一个,但这只是我的首选项,感谢您将它添加为评论! – FanaHOVA

+0

我喜欢你的答案 - 绝对是最简单的方法,但@abax得到了我需要的东西 – jfr

相关问题