我在Rails中向模型添加方法时出现未定义的方法错误

时间:2013-04-03 23:18:44

标签: ruby-on-rails rails-activerecord

我有错误

#<Class:0x429c840>

的未定义方法events_and_repeats'

app / controllers / events_controller.rb:11:在`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

有什么问题?

3 个答案:

答案 0 :(得分:10)

就像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

答案 1 :(得分: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

答案 2 :(得分: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>

Class method and Instance method