Find_all_by.association

Rails 3.1.3

I have tables

User => has_many :contribution
Contribution => belongs_to :user

in user.rb, I would like to define a method to compute the total
contribution
(sum of field ‘price:integer’ )

def total_contribution
@contributions = Contribution.find_all_by_user(self)
total = 0
@contributions.each do |c|
if c.done
total += c.price
end
end
return total
end

“Contribution.find_all_by(self)” gives an error

undefined method `find_all_by’ for

Is there any better way?

soichi

Thanks for your answer. but it gives a different error

SQLite3::SQLException: no such column: contributions.user_id: SELECT
“contributions”.* FROM “contributions” WHERE “contributions”.“user_id”
= 3

Maybe the association is not properly set up?

soichi

On 30 April 2012 09:24, Soichi I. [email protected] wrote:

Please don’t top post, it makes it difficult to follow the thread.
Insert your reply at appropriate point(s) in previous message. Thanks

Thanks for your answer. but it gives a different error

SQLite3::SQLException: no such column: contributions.user_id: SELECT
“contributions”.* FROM “contributions” WHERE “contributions”.“user_id”
= 3

Maybe the association is not properly set up?

Is there a column user_id in the contributions table? You should have
added one for the the belongs_to association.

I think it would be worth your while working right through some
tutorials on Rails in order better to understand the basics of Rails.
railstutorial.org is good and free to use online.

Colin

On 30 April 2012 09:03, Soichi I. [email protected] wrote:

Rails 3.1.3

I have tables

User => has_many :contribution

That should be :contributions, plural.

Contribution => belongs_to :user

in user.rb, I would like to define a method to compute the total
contribution
(sum of field ‘price:integer’ )

def total_contribution
@contributions = Contribution.find_all_by_user(self)

Just use
@contributions = self.contributions

Colin

Please don’t top post, it makes it difficult to follow the thread.
Insert your reply at appropriate point(s) in previous message.

Sorry about that. I will be careful.

Is there a column user_id in the contributions table? You should have
added one for the the belongs_to association.

I was thinking of id of User table (created by Devise) rather than the
‘user_id’ which are supposed to be attached to ‘Contribution’ table.
Stupid misunderstanding of mine :wink:

tutorials on Rails in order better to understand the basics of Rails.
railstutorial.org is good and free to use online.

Thanks for the info.

soichi