Reputation: 15394
I cant seem to get the result of a scope to display in my view as i get this error message.I am trying to get all of the memberships amounts for the day added up and displayed as a total
missing attribute: membership_id
My Models and scope
class Member < ActiveRecord::Base
belongs_to :membership
accepts_nested_attributes_for :membership
attr_accessible :membership_id, :forename, :middlename, :surname, :house_no, :house_name, :street, :town, :postcode, :home_tel, :mobile_tel, :work_tel, :email, :start_date, :expiry_date
scope :new_memberships_cash_today, ->() {
joins(:membership).where(:start_date => Date.today).select('ROUND(SUM(memberships.cost), 2)')
}
end
class Membership < ActiveRecord::Base
has_many :members, :dependent => :destroy
attr_accessible :membership_type, :cost
end
And then my view
columns do
#Total amount in £ for New Memberships today
column do
panel "Cash Today", :class => 'NewAmountMemberships' do
table_for Member.new_memberships_cash_today do
column 'Total cash' do |c|
c.membership.map { |e| [e.cost, e.id] }
end
end
end
end
end
After some reading it would seem that there may be an issue with my select call in the scope, as i need to specify all of the models attributes to make a successful call with Active Record?
As i am performing a sum within the select i am unsure how to add more attributes, if this is even the case
Any help appreciated
i have run the scope in the the console and this is what is returned
Member Load (0.1ms) SELECT ROUND(SUM(memberships.cost), 2) FROM `members` INNER JOIN `memberships` ON `memberships`.`id` = `members`.`membership_id` WHERE `members`.`start_date` = '2013-12-13'
=> #<ActiveRecord::Relation [#<Member id: nil>]>
Upvotes: 2
Views: 3609
Reputation: 15927
I wouldn't do this in a scope, but in a helper method. That way you can grab the associated records and just call your method to return the total.
Something along the lines of this:
def membership_sum(memberships = [])
sum = 0
memberships.each { |membership| sum += membership.cost }
sum.round
end
Now, store the associated records in a @memberships variable (from within your controller) and then, in your view, use <%= membership_sum(@memberships) %>
Upvotes: 2