I have a Rails 2.3.11 app which has two key Models:
- Activity
- Transaction
Live site: http://iatidata.heroku.com
Github: https://github.com/markbrough/IATI-DataEvery transaction nests under an activity. Each activity has multiple transactions.
I think I've got confused about how associations work in Rails, but maybe what I'm trying to do isn't possible.
Essentially, I want to get the total value of the transactions of all 开发者_JS百科the activities which belong to each country. So how much money went to India, how much to Afghanistan, etc.
This works:
@thiscountry_activities.each do |a|
@thiscountry_value = @thiscountry_value + a.transactions.sum(:value)
end
But this doesn't work:
@thiscountry_value = @thiscountry_activities.transactions.sum(:value)
It gives this error:
undefined method `transactions' for #<Array:0xb5670038>
@thiscountry_activities is defined like this:
@activities = Activity.find(:all, :conditions=> @conditions)
This is placed within a loop which gets each recipient country code. @conditions are :
@conditions[:recipient_country_code]=*each recipient country code, e.g. AF*
Looks like I have some sort of association problem. This is how the models are set up:
class Transaction < ActiveRecord::Base
belongs_to :activity
end
class Activity < ActiveRecord::Base
has_and_belongs_to_many :policy_markers
has_and_belongs_to_many :sectors
has_many :transactions
end
I think this is probably quite a simple problem, but I can't work out what's going on. The two models are connected together via id (in Activity) and activity_id (in Transactions).
Thank you!
Nothing is broken, the find
method in Rails2 returns an Array - and there is no transactions
method on the Array class. Use the first thing you have that's working, with the each
iterator, or work from the other side - from Transaction
and grouping by the activity. It's been a while since I wrote Rails2 code, but it'll be something like this:
Transaction.all( :select => "activity_id, SUM(value) AS total", :group => 'activity_id' )
That's not ready to copy-paste into your app as-is because there are some things about your app which aren't clear to me, but hopefully it sets you in the right direction.
精彩评论