views:

82

answers:

1

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.

+2  A: 
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.

cwninja
Thanks, but I forgot some important info - I've added another requirement.
nfm
Answer updated.
cwninja
For the record, the linked answer uses named scopes: http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html
nfm