Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
Gabi Avatar asked Apr 03 '13 23:04

Gabi


People also ask

What does undefined method mean in Ruby?

This is a common Ruby error which indicates that the method or attribute for an object you are trying to call on an object has not been defined.

Can we call controller method in model rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended.

What does it mean when a method is undefined in Java?

The problem is that the method has the same name as the class and has no return type. Therefore, from the compiler's point of view, it's a constructor rather than an ordinary method. And a constructor can't call itself in the manner your method is trying to. Rename the method and add a return type.


2 Answers

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.

like image 128
Zippie Avatar answered Oct 02 '22 19:10

Zippie


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
like image 43
Luís Ramalho Avatar answered Oct 02 '22 18:10

Luís Ramalho