【问题标题】:can't get model to properly validate无法让模型正确验证
【发布时间】:2015-10-03 08:50:57
【问题描述】:

我有以下型号。这可行,但是当我不填写代表或重量时,我不断收到错误消息:undefined method `*' for nil:NilClass

这在 calculate_tonnage 方法中。

有没有办法让我检查是否存在代表或重量,然后计算吨位 en 然后检查吨位是否唯一。

我认为这是解决方案,但我找不到如何做到这一点。有没有人知道解决这个问题的最佳方法是什么?

class Submission < ActiveRecord::Base
  belongs_to :user
  belongs_to :contest

  validates_presence_of :user_id, :reps, :weight
  validates_uniqueness_of :tonnage, scope: [:user_id, :contest_id]

  after_validation :calculate_tonnage

  # model helpers
  def calculate_tonnage
    self.tonnage = self.weight * self.reps
  end

end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord models


    【解决方案1】:

    当然,只需将您的代码更改为:

      def calculate_tonnage
        self.tonnage = weight * reps if weight && reps
      end
    

    【讨论】:

    • 我可以在您的答案中添加对实例/类数据的解释吗?我会自己写,但似乎没有必要
    • 你也可以把这个逻辑放在验证声明上:validates_uniqueness_of :tonnage, scope: [:user_id, :contest_id], if: "weight &amp;&amp; reps"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2012-10-13
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多