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?
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.
As the two answers said, you should not be calling controller methods from your models. It is not recommended.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With