【问题标题】:'NoMethodError: undefined method' in Ruby on Rails ModelRuby on Rails 模型中的“NoMethodError:未定义方法”
【发布时间】:2015-06-14 23:23:11
【问题描述】:

我正在创建一个每月定期付款的系统,因此我正在使用 whenever gem

创建一个新的付款要求

问题似乎出在我的付款模型方法中,就在这里。

class Payment < ActiveRecord::Base
  belongs_to :client

  def monthly_payment
    clients = Client.all
    clients.each do |client|
      Payment.create(month: Date.now, client_id: client.id)
    end
  end
end

在 cron.log 中,我得到了 NoMethodError,所以我在 rails 控制台中尝试了该方法,但出现了同样的错误:

NoMethodError: undefined method `monthly_payment' for Payment (call 'Payment.connection' to establish a connection):Class

模型有问题吗?

这里是支付的架构:

create_table "payments", force: :cascade do |t|
 t.date     "date"
 t.string   "type"
 t.date     "month"
 t.boolean  "paid"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.integer  "client_id"
end

【问题讨论】:

  • 在 cron 中运行调用 Payment 模型中代码的命令是什么?

标签: ruby-on-rails methods model nomethoderror whenever


【解决方案1】:

你必须使用类方法,而不是实例方法:

def self.monthly_payment # notice the self.
  clients = Client.all
  clients.each do |client|
    Payment.create(month: Date.now, client_id: client.id)
  end
end

这样你就可以打电话了

Payment.monthly_payment # class method
# method that can be called only on the Payment class

不是

Payment.where(some_condition).first.monthly_payment # instance method
# method that can be called only on an instance of the Payment class

一个有趣的链接:http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

【讨论】:

  • 我的愚蠢错误。总之非常感谢!我没有意识到这一点。
【解决方案2】:

尝试将其定义为类方法,即

def Payment.monthly_payment
  # etc.
end

抱歉,格式错误,我使用的是移动设备。

【讨论】:

  • (我得到了你的支持,我编辑了你的帖子以格式化代码)
  • 好像当我在手机上写这篇文章时,有人手指更快:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多