Reputation: 4740
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?
Upvotes: 0
Views: 54
Reputation: 83680
@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
Upvotes: 2
Reputation: 2890
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.
Upvotes: 1