在 Rails 4 中找到一组深度嵌套的子对象的所有父对象
Find all parent's parents of a set of deeply nested child objects in Rails 4
这听起来可能令人困惑,但很容易解释。假设我有这 3 个深度嵌套模型:
//boo.rb
class Boo < ActiveRecord::Base
has_many :foos
end
//foo.rb
class Foo < ActiveRecord::Base
belongs_to :boo
has_many :goos
end
//goo.rb
class Foo < ActiveRecord::Base
belongs_to :foo
end
现在,如果我在 @goos
中获得了一组 Goos,是否有可能以一种精简的方式获得所有连接的 Foos?我正在使用这个 atm,但它不是很精简,因为我只在第一步中获得了 id 而不是对象本身:
@goos.pluck(:foo_id)
如果有更好的方法来做到这一点,是否还有一种方法可以获取连接的 Foos 的所有父级?这样我就有了一组连接到 @goos
?
中的对象的所有 Boos
希望这个问题不会太奇怪,但我不确定是否有相关的技术术语!
像这样工作:
#Get all Foos
@foos = @goos.map(&:foo).compact.uniq
#Get all Boos
@boos = @goos.map(&:foo).map(&:boo).compact.uniq
尽管它不是很好,因为它 return 是一个数组而不是活动记录关系,这意味着我不能在其上调用 where
和 order
。
编辑:
如果出于某种原因保留活动记录关系很重要 class,这是更好的方法:
#Get all Foos
@foos = Foo.where(id: @goos.map(&:foo.id).uniq)
#Get all Boos
@boos = Boo.where(id: @goos.map(&:foo).map(&:boo_id).uniq)
这听起来可能令人困惑,但很容易解释。假设我有这 3 个深度嵌套模型:
//boo.rb
class Boo < ActiveRecord::Base
has_many :foos
end
//foo.rb
class Foo < ActiveRecord::Base
belongs_to :boo
has_many :goos
end
//goo.rb
class Foo < ActiveRecord::Base
belongs_to :foo
end
现在,如果我在 @goos
中获得了一组 Goos,是否有可能以一种精简的方式获得所有连接的 Foos?我正在使用这个 atm,但它不是很精简,因为我只在第一步中获得了 id 而不是对象本身:
@goos.pluck(:foo_id)
如果有更好的方法来做到这一点,是否还有一种方法可以获取连接的 Foos 的所有父级?这样我就有了一组连接到 @goos
?
希望这个问题不会太奇怪,但我不确定是否有相关的技术术语!
像这样工作:
#Get all Foos
@foos = @goos.map(&:foo).compact.uniq
#Get all Boos
@boos = @goos.map(&:foo).map(&:boo).compact.uniq
尽管它不是很好,因为它 return 是一个数组而不是活动记录关系,这意味着我不能在其上调用 where
和 order
。
编辑:
如果出于某种原因保留活动记录关系很重要 class,这是更好的方法:
#Get all Foos
@foos = Foo.where(id: @goos.map(&:foo.id).uniq)
#Get all Boos
@boos = Boo.where(id: @goos.map(&:foo).map(&:boo_id).uniq)