6

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Gabi
  • 250
  • 1
  • 4
  • 13

3 Answers3

12

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.

Zippie
  • 6,018
  • 6
  • 31
  • 46
  • Thanks a lot!! May be you may help me resolve one more issue http://stackoverflow.com/questions/15790909/gem-ice-cube-for-reccurence-events – Gabi Apr 03 '13 at 23:55
4

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
Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67
  • 1
    Thank you! Now I will know it ) – Gabi Apr 04 '13 at 00:07
  • 1
    You're welcome! A couple of thing, you don't need the `@events`at all, ruby methods will return the last evaluated statement. Moreover, `self.where()` is also not necessary because you're calling `where()` already inside `self`. Glad I was able to help you! – Luís Ramalho Apr 04 '13 at 00:09
0

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

S.M.Mousavi
  • 5,013
  • 7
  • 44
  • 59