1

为什么这不起作用?

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
4

3 回答 3

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)
于 2013-01-18T09:30:00.350 回答
0

您不能self.notes在类方法中调用它,因为它读取为Customer.notes您想要“Customer.new.notes”的位置。

所以你必须做类似以下的事情

更改def self.called_this_monthdef called_this_month

或者

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
于 2013-01-18T09:19:55.737 回答
0

notes不是类方法,是实例方法。如果您需要一个范围notes,请将其放入Notes模型中并使用类似的东西

def self.called_this_month
  where(:id => Notes.called_this_month.pluck(:customer_id).uniq)
end
于 2013-01-18T09:20:19.483 回答