Undefined method error when adding a method to a model in Rails

I have a mistake

undefined event_and_repeats' method for #<Class:0x429c840>

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

my application /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

application / controllers / 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

What's wrong?

+5
source share
3 answers

As Swards said, you called the instance method for the class. Rename it:

def self.events_and_repeats(date)

I only write this in response because it is too long for comment, check the github page of the ice cube, it strictly says:

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

Also I think that you do not need requirein your model.

+10
source

You can do this in both directions:

class Event < ActiveRecord::Base
  ...

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

end

or

class Event < ActiveRecord::Base
  ...

  def self.events_and_repeats(date)
    where(shedule:date.beginning_of_month..date.end_of_month)
  end    
end
+4
source

:

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>

0
source

All Articles