2013-04-03 19 views
5

mam Błądniezdefiniowany błąd metoda kiedy dodać metodę modelowania w Rails

niezdefiniowanych events_and_repeats metoda dla #<Class:0x429c840>

app/controllers/events_controller.rb: 11: w indeksie `”

mój app/models/event.rb jest

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 

Co jest nie tak?

+7

prostu trzeba „ja” - dokonane metodę instancji, ale nazywa się metoda klasy – Swards

+0

Własna gdzie? Proszę podać mi przykład. I jaka jest różnica? Dzięki – Gabi

+0

Sprawdź odpowiedź Zippie, myślę, że wszystko tam jest pokryte. – Swards

Odpowiedz

10

Podoba muraw powiedział pan nazywa metodę instancji w klasie. Przemianować go:

def self.events_and_repeats(date) 

Ja tylko pisanie to na odpowiedź, ponieważ jest zbyt długi dla komentarza, checkout strona na lód GitHub, jest ściśle mówi:

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

Także myślę, że nie potrzebujesz require w swoim modelu.

+0

Wielkie dzięki! Być może pomóż mi rozwiązać jeszcze jeden problem http://stackoverflow.com/questions/15790909/gem-ice-cube-for-reccurence-events – Gabi

+0

bez problemu, dziękuję Swards za pierwszą część :) – Zippie

4

Można zrobić to w obie strony:

class Event < ActiveRecord::Base 
    ... 

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

end 

lub

class Event < ActiveRecord::Base 
    ... 

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

Dziękujemy! Teraz to poznam) – Gabi

+0

Nie ma za co! Kilka rzeczy, nie potrzebujesz '@ events'at all, metody ruby ​​zwrócą ostatnią ocenioną instrukcję. Co więcej, 'self.where()' również nie jest konieczne, ponieważ wywołujesz 'where()' już wewnątrz 'self'. Cieszę się, że mogłem ci pomóc! –

0

Tylko dla większej jasności:

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

Powiązane problemy