Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the value to null through rails model?

how to make a column value to null through model in ruby on rails? For example, I have a checkbox called 'include_on_epc' and the textbox called 'removal_reason'.

If the checkbox is checked, I want to set the value of the textbox should be NULL in database.

I tried the following, its not working.

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
like image 998
Sri Avatar asked Dec 21 '22 11:12

Sri


1 Answers

Two issues here.

  1. As Jakob pointed out, self.removal_reason == nil compares removal_reason to nil, and you want to set removal_reason to nil. Therefore self.removal_reason = nil is definitely what you want here.

  2. If include_on_epc is a boolean column, comparing to 1 is not going to work. You probably want a simple if include_on_epc because its values are likely true or false, not 1 or 0, and in Ruby 1 != true.

like image 85
Andrew Haines Avatar answered Dec 29 '22 14:12

Andrew Haines