I have such model structure:
class User < ActiveRecord::Base
has_many :groups, :through => :user_groups
has_many :orders
has_many :user_groups
end
–
class UserGroup < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
–
class Group < ActiveRecord::Base
has_many :user_groups
has_many :users, :through => :user_groups
end
In model group i have field markup.
How can i for every user via it’s user_groups get group’s markup field?
I try so:
user.user_groups.each do |u|
summ += u.groups.markup
end
Sure it is not working… But how to fetch data from third model?
user.groups.map(&:markup).sumshould do it just fineEDIT:
I used #flat_map because I was thinking that it was a nested array. But has_many :through would combine it into a single result list, so #map will be fine
EDIT2:
In discussion with @VladisAzamaris, it was pointed out that the
markupcolumn is a float, sosumis more appropriate thanjoin