`undefined Method`用于has_many关系?

时间:2013-01-18 09:06:29

标签: ruby-on-rails has-many

为什么这不起作用?

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

3 个答案:

答案 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)