简体   繁体   English

如何从模型中调用方法?

[英]How to call method from model?

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. 我也尝试过将我的方法放在Controller中,但无法正常工作。 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? 有什么想法我可以称呼它吗?

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 您需要通过执行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. 用您当前的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM