如何通过rails模型将值设置为null?

Sri*_*Sri 3 ruby ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

如何通过rails上的ruby中的模型使列值为null?例如,我有一个checkbox被叫'include_on_epc'textbox被叫'removal_reason'.

如果选中该复选框,我想设置文本框的值应该在数据库中为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
Run Code Online (Sandbox Code Playgroud)

And*_*nes 7

这里有两个问题.

  1. 正如雅各布指出,self.removal_reason == nil相比较removal_reasonnil,并且要设置 removal_reasonnil.因此,self.removal_reason = nil这绝对是你想要的.

  2. 如果include_on_epcboolean列,则比较1不起作用.你可能想要一个简单的if include_on_epc因为它的值可能是,true或者false不是,1或者0在Ruby中1 != true.