【问题标题】:How to set the value to null through rails model?如何通过rails模型将值设置为null?
【发布时间】:2013-01-14 10:42:19
【问题描述】:

如何通过 ruby​​ on rails 中的模型使列值为空?例如,我有一个名为'include_on_epc'checkbox 和一个名为'removal_reason'textbox

如果复选框被选中,我想将文本框的值设置为数据库中的 NULL。

我尝试了以下方法,但它不起作用。

class Emm::Rrr::Result < ActiveRecord::Base

  before_save :no_removal_reason_when_including_on_epc

  private
  def no_removal_reason_when_including_on_epc
    if include_on_epc == 1
      self.removal_reason == nil
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    这里有两个问题。

      1234563因此self.removal_reason = nil绝对是你想要的。
    1. 如果include_on_epcboolean 列,则与1 进行比较是行不通的。您可能想要一个简单的if include_on_epc,因为它的值可能是truefalse,而不是10,在Ruby 中是1 != true

    【讨论】:

    • 酷...它的工作。您的第二点有效!...感谢您更新自己的详细答案。非常感谢安迪....
    【解决方案2】:

    看来self.removal_reason == nil 应该是self.removal_reason = nil。我猜你想要分配,而不是在那条线上的比较。 ;-)

    【讨论】:

    • include_on_epc 可能是“1”而不是 1。尝试 if include_on_epc.to_i == 1 或检查字符串,看看是否有任何区别
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多