2014-03-19 61 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会补充说明明确清楚返回的内容。 –

相关问题