Gabi
Gabi

Reputation: 250

Undefined method error when I add method to model in Rails

I have the error

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

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

my app/models/event.rb is

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

app/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 is wrong?

Upvotes: 6

Views: 10216

Answers (3)

S.M.Mousavi
S.M.Mousavi

Reputation: 5226

Just for more clarity:

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

Upvotes: 0

Zippie
Zippie

Reputation: 6088

Like Swards said, you called a instance method on a class. Rename it:

def self.events_and_repeats(date)

I am only writting this in an answer because it's too long for a comment, checkout the ice-cube github page, it strictly says:

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

Also i think it you don't need the require in your model.

Upvotes: 12

Lu&#237;s Ramalho
Lu&#237;s Ramalho

Reputation: 10198

You can do it both ways:

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

Upvotes: 4

Related Questions