5

我有错误

未定义的方法 events_and_repeats' for#<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

就像斯沃兹所说,你在一个类上调用了一个实例方法。重命名它:

def self.events_and_repeats(date)

我只是在答案中写这个,因为评论太长了,查看 ice-cube 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 回答