【问题标题】:How to call method from model?如何从模型中调用方法?
【发布时间】:2014-04-25 23:18:06
【问题描述】:

我正在尝试从我的模型中调用一个方法:

<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

我怎么称呼它的任何想法?

【问题讨论】:

    标签: ruby-on-rails ruby methods model call


    【解决方案1】:
    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)
    

    用你目前的方法。

    【讨论】:

    • 你不需要明确的return
    • 意识到这一点,但我复制并粘贴以显示类方法。它不会伤害任何东西,也许 OP 添加了它以明确返回什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2014-08-27
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多