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

「Customer.new.notes」が必要な場所としてself.notes読み取られるため、クラスメソッドで呼び出すことはできません。Customer.notes

だからあなたは次のようなことをしなければなりません

def self.called_this_monthに変更def 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 に答える