bosticko
bosticko

Reputation: 833

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?

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:

Foo.first
  .bars.joins(:foos) # => ActiveRecord::Relation [Bar, Bar, Bar...]

How can the query be made to return an ActiveRecord::Relation [Foo, Foo, Foo...]?

Upvotes: 0

Views: 30

Answers (1)

lusketeer
lusketeer

Reputation: 1930

Give this a shot

Foo.joins(:bars).merge(Foo.first.bars).uniq

Upvotes: 1

Related Questions