[英]Retrieve as Model in Active Record
Is it possible to take the results of any arbitrary query and cast them to any ActiveRecord::Base
model, without using Base.connection.execute
? 是否可以不使用
Base.connection.execute
就可以将任何查询的结果转换为任何ActiveRecord::Base
模型?
For example, given these models: 例如,给定以下模型:
class Foo < ActiveRecord::Base
has_and_belongs_to_many :bars
end
class Bar < ActiveRecord::Base
has_and_belongs_to_many :foos
end
If we run the a query like this, which loops back, we are stuck with Bar
objects: 如果我们运行像这样的查询,该查询将循环返回,那么我们将陷入
Bar
对象:
Foo.first
.bars.joins(:foos) # => ActiveRecord::Relation [Bar, Bar, Bar...]
How can the query be made to return an ActiveRecord::Relation [Foo, Foo, Foo...]
? 如何进行查询以返回
ActiveRecord::Relation [Foo, Foo, Foo...]
?
试一下
Foo.joins(:bars).merge(Foo.first.bars).uniq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.