0

I'm developing a web application about gift lists in Rails 3. I'd would like to get all the purchases for a certain list. These are the models and their relationships:

class Gift < ActiveRecord::Base
  belongs_to :list
  has_many :purchases

class List < ActiveRecord::Base
  has_many :gifts

class Purchase < ActiveRecord::Base
  belongs_to :gift

So, basically, I've tried the following code (I don't think it's the best way to do this at all), and eventhough the results are correct, I've realized that I get a Gift object instead of a Purchase:

@purchases = List.find(params[:id]).gifts.joins(:purchases).select("purchases.*")

Any ideas?

2 Answers 2

2
@purchases = List.find(params[:id]).
                  gifts.joins(:purchases).
                  map(&:purchases).flatten

or just refactor your models:

class List < ActiveRecord::Base
  has_many :gifts
  has_many :purchases, :through => :gifts

so

List.find(params[:id]).purchases
Sign up to request clarification or add additional context in comments.

1 Comment

That what I was looking for! I've added the :purchases relation to the List model.
1

If you want all the purchases maybe...

@purchases= List.find(params[:id]).gifts.collect{|g| g.purchases}

Although you may want to split it up and check that List.find returns a valid List.

1 Comment

Although I prefer the refactor that @fl00r answered

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.