5

エラーがあります

未定義のメソッド events_and_repeats' の#<Class:0x429c840>

app/controllers/events_controller.rb:11:in `index'

私の app/models/event.rb は

class Event < ActiveRecord::Base
  belongs_to :user

  validates :title, :presence => true,
                    :length => { :minimum => 5 }
  validates :shedule, :presence => true

  require 'ice_cube'
  include IceCube

  def events_and_repeats(date)
    @events = self.where(shedule:date.beginning_of_month..date.end_of_month)

    return @events
  end

end

アプリ/コントローラー/events_controller.rb

def index
    @date = params[:month] ? Date.parse(params[:month]) : Date.today
    @repeats = Event.events_and_repeats(@date)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @events }
    end
  end

なにが問題ですか?

4

3 に答える 3

11

Swards が言ったように、クラスのインスタンス メソッドを呼び出しました。名前を変更します。

def self.events_and_repeats(date)

コメントするには長すぎるため、これを回答に書いているだけです。アイスキューブのgithubページをチェックしてください。厳密には次のように書かれています。

Include IceCube inside and at the top of your ActiveRecord model file to use the IceCube classes easily.

requireまた、モデルには必要ないと思います。

于 2013-04-03T23:26:20.710 に答える
4

両方の方法で実行できます。

class Event < ActiveRecord::Base
  ...

  class << self
    def events_and_repeats(date)
      where(shedule:date.beginning_of_month..date.end_of_month)
    end
  end

end

また

class Event < ActiveRecord::Base
  ...

  def self.events_and_repeats(date)
    where(shedule:date.beginning_of_month..date.end_of_month)
  end    
end
于 2013-04-03T23:25:53.093 に答える
0

より明確にするために:

class Foo
  def self.bar
    puts 'class method'
  end

  def baz
    puts 'instance method'
  end
end

Foo.bar # => "class method"
Foo.baz # => NoMethodError: undefined method ‘baz’ for Foo:Class

Foo.new.baz # => instance method
Foo.new.bar # => NoMethodError: undefined method ‘bar’ for #<Foo:0x1e820>

クラスメソッドとインスタンスメソッド

于 2015-09-28T07:45:52.037 に答える