缺少属性错误Rails

时间:2013-12-13 14:39:39

标签: ruby-on-rails ruby activerecord scope

我似乎无法在我的视图中显示范围的结果,因为我收到此错误消息。我正在尝试将当天的所有会员资格金额相加并显示为总计

missing attribute: membership_id

我的模型和范围

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

然后是我的观点

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

经过一些阅读后,似乎我的选择调用可能存在问题,因为我需要指定所有模型属性以使用Active Record成功调用?

由于我在选择中执行总和,我不确定如何添加更多属性,如果是这样的话

任何帮助表示赞赏

我在控制台中运行了范围,这是返回的内容

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>]>

1 个答案:

答案 0 :(得分:2)

我不会在范围内执行此操作,而是使用辅助方法。这样你就可以获取相关的记录,只需调用你的方法来返回总数。

有些事情如下:

def membership_sum(memberships = [])
  sum = 0
  memberships.each { |membership| sum += membership.cost }
  sum.round
end

现在,将相关记录存储在@memberships变量中(来自您的控制器内),然后在您的视图中使用<%= membership_sum(@memberships) %>