2014-03-19 60 views
0

我想從我的模型調用一個方法有:如何從模型中調用方法?

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

我也試圖把我的方法在我的控制器,但它不會工作。 但我只是得到這個錯誤:

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 

這裏是我的模型:

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 

任何想法如何,我可以打電話了嗎?

回答

5
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 

你需要做self.method_name

其實這是行不通的,使之類的方法,並沒有注意到國家代碼。保持原樣,但你需要一個國家的實例來調用它。

所以,如果你控制器,你有

@country = Country.first 

然後,您可以做

@country.all_holidays_in(2014) 

根據您當前的方法。

+0

你不需要明確的'return' – bjhaid

+0

意識到這一點,但我複製並粘貼顯示類的方法。它不會傷害任何東西,也許OP會補充說明明確清楚返回的內容。 –

相關問題