jwarzech
jwarzech

Reputation: 6665

Rails 3 scope only select certain attributes for a has_many relationship

This looks like it should be something pretty easy but I can't seem to get it to work. I have a model with a has_many relationship and I'd like a scope on the parent that allows me to select only certain attributes for each.

An example:

class Bakery < ActiveRecord::Base
  has_many :pastries
  scope :summary, select([:id, :name, 'some option calling pastries.summary'])

class Pastry < ActiveRecord::Base
  belongs_to :bakery
  scope :summary, select([:id, :image_url])

I'd like to be able to call something like Bakery.first.summary and get a Bakery model with only the id and name populated and for each pastry in it's pastries array to only have the id and image_url attributes populated.

Upvotes: 0

Views: 1166

Answers (1)

stef
stef

Reputation: 14268

You could do this, but it won't affect the SQL queries that are made as a result (assuming you're trying to optimise the underlying query?):

class Pastry
  ...
  def summary
    {
      :id => self.id,
      :image_url => self.image_url
    }
  end
end

class Bakery
  ...
  def summary     
    pastries.collect {|i| i.summary }
  end
end

This would then give you an array of hashes, not model instances.

ActiveRecord doesn't behave how you're expecting with models - it will fetch whatever data it thinks you need. You could look at using the Sequel gem instead, or executing a raw SQL query such as:

Pastry.find_by_sql("SELECT id, name from ...")

But this could give you unexpected behaviour.

Upvotes: 1

Related Questions