开发者

Pull objects from an association into an array in Rails

A user has_many :donations, a project has_many :donations, and a donation belongs_to :user and belongs_to :project.

I'm looking for a sensible way to extract the projects associated with a user (through donations) into an array.

I'm currently doing:

def index
  @user = User.find params[:user_id]
  @projects = []
  @user.donations.each do |donation|
    @projects << donation.project
  end
end

I feel like I'm missing something obvious, as this seems lame. Is there a better way to do this?

Edit

I accidentally simplified this too far. A user can also be associated with a project through other开发者_开发知识库 models, so @projects = @user.projects isn't going to do what I need it to.


class User < AR::Base
  has_many :donations
  has_many :projects, :through => :donations
  …
end

@user.projects

should work.

For gathering many association collections see my previous answer. You will need to adapt it to use the through associations (just treat them as normal has_masnys), but the same applies.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜