为什么这不起作用?
class Customer < ActiveRecord::Base
has_many :notes, :class_name => "CustomerNote", :foreign_key => 'customer_id'
def self.called_this_month
self.notes.where(:date => Date.today.beginning_of_month..Date.today.end_of_month).count
end
end
我收到此错误:
undefined method `notes` for #<Class:0x00000004b37190>
注意型号:
class CustomerNote < ActiveRecord::Base
self.table_name = "customer_contact"
belongs_to :customer
end
答案 0 :(得分:0)
你不能在类方法中调用self.notes
,因为它读作Customer.notes
,你想要'Customer.new.notes'。
因此您必须执行以下操作
将def self.called_this_month
更改为def called_this_month
OR
self.notes.where(:date => Date.today.beginning_of_month..Date.today.end_of_month).count
到
Customer.first.notes.where(:date => Date.today.beginning_of_month..Date.today.end_of_month).count
答案 1 :(得分:0)
notes
不是类方法,它是一个实例方法。如果您需要notes
上的范围,请将其放在Notes
模型中并使用类似
def self.called_this_month
where(:id => Notes.called_this_month.pluck(:customer_id).uniq)
end
答案 2 :(得分:0)
<强>型号:强>
class Customer < ActiveRecord::Base
def self.called_this_month(customer)
customer.notes.where(:date => Date.today.beginning_of_month..Date.today.end_of_month).count
end
end
<强>控制器:强>
@customer = Customer.find(params[:customer_id])
//this will give you the count of the method call as output.
@count = Customer.called_this_month(@customer)