开发者

How to build the following query

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开发者_如何学Python 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?


@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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜