Frage

I'm trying to call a method from my model with:

<p>
<strong>Holidays this year:</strong>
<%= Country.all_holidays_in(2014) %>
</p>

I have also tried putting my methods in my Controller, but it won't work. But I just get this Error:

NoMethodError in Countries#show

Showing C:/xampp/htdocs/fluxcapacitor/app/views/countries/show.html.erb where line #15 raised:

undefined method `all_holidays_in' for Country(id: integer, name: string, countrycode: string):Class

Here's my model:

class Country < ActiveRecord::Base

  has_and_belongs_to_many :groups

  validates :name, presence: true 
  validates :countrycode, presence: true

  def all_holidays_in(y)                                
    from = Date.civil(y,1,1)                                                            
    to = Date.civil(y,12,31)                                                            
    return Holidays.between(from, to, self.countrycode)                                     
   end
end

Any Ideas how I can call it?

War es hilfreich?

Lösung

def self.all_holidays_in(y)                              #
    from = Date.civil(y,1,1)                                                            #
    to = Date.civil(y,12,31)                                                            #
    return Holidays.between(from, to, self.countrycode)                                     
end

You need to make it a class method by doing self.method_name

In fact that won't work, hadn't noticed the country code. Leave the method as it is but you need an instance of the country to call it.

So if in you controller you have

@country = Country.first

You can then do

@country.all_holidays_in(2014)

With your current method.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top