2013-04-03 86 views
5

我有錯誤未定義方法錯誤,當我添加方法中的Rails

未定義的方法events_and_repeats模型的#<Class:0x429c840>

應用程序/控制器/ events_controller.rb:11:在`索引」

我的應用程序/模型/ 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 

應用程序/控制器/ 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 

出了什麼問題?

+7

只是需要一個「自我」 - 你讓一個實例方法,而是叫做類方法 – Swards 2013-04-03 23:21:42

+0

自哪裏?請給我一個例子。有什麼區別?謝謝 – Gabi 2013-04-03 23:24:43

+0

檢查Zippie的迴應,我認爲它覆蓋了那裏。 – Swards 2013-04-03 23:30:47

回答

10

像Swards說,你叫上一個類的實例方法。其重命名爲:

def self.events_and_repeats(date) 

我只是在回答書面方式,是因爲它是一個評論過長, 結賬的冰塊GitHub的頁面,它嚴格地說:

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

此外,我認爲這您的模型中不需要require

+0

非常感謝!可能是你可能會幫助我解決一個問題http://stackoverflow.com/questions/15790909/gem-ice-cube-for-reccurence-events – Gabi 2013-04-03 23:55:40

+0

沒問題,感謝Swards的第一部分:) – Zippie 2013-04-03 23:59:26

4

你可以做到兩者兼得:

class Event < ActiveRecord::Base 
    ... 

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

end 

class Event < ActiveRecord::Base 
    ... 

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

謝謝!現在我知道了) – Gabi 2013-04-04 00:07:03

+0

不客氣!有幾件事情,你不需要'@ events',ruby方法會返回最後一條評估語句。而且,'self.where()'也不是必須的,因爲你在'self'內調用'where()'。很高興我能夠幫助你! – 2013-04-04 00:09:53

0

只是爲了更清晰:

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