2

In my model i have the following bit of code.

 hash_values = JSON.parse(question_hash)
 hash_values.each do |k,v|
   b = UpdateData.new
   b.question, b.answer, b.phase = v[0].to_i, v[1], v[2].to_i
   b.save!
 end

I have a problem of phase value. b.phase has an id of 0 to 5 and it also should be null. When the data is not entered for the phase the value is ""(.to_i = 0) it considered as 0 in database. I need to store an null value rather than 0 if phase value is "".

3 Answers 3

2

Just check if the string is empty:

if v[2].empty?
  b.phase = nil
else
  b.phase = v[2].to_i
end

or a nice one liner using a ternary operator:

p.phase = v[2].empty? ? nil : v[2].to_i
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

hash_values.each do |k,v|
  b = UpdateData.new
  b.question, b.answer = v[0].to_i, v[1]
  b.phase = v[2].blank? ? nil : v[2].to_i
  b.save!
end

3 Comments

hi... thanks... and one doubt... will you explain me why we using double question mark after blank? am very new to ruby on rails..
The method name is blank? so that is one question mark, the other is due to the ternary operator (or 'inline if statement')
thats true @Veger, and unlike empty?, "".blank? and nil.blank? both will return true
1

There is a gem that can do that for you automatically for every attributes existing in your model :

Add this to your Gemfile and run bundle install :

gem 'nilly_vanilly'

This gem will convert any empty string into a NIL value to be store into your DB.

====== UPDATE =====

I just tried this Gem and it is not working. I reported it, and the developper said there was an incompatibility with postgreSQL. He is patching the gem. In the time being, I end up with creating my own library.

Just create the file lib/my_model_tools.rb containing the following lines :

module MyModelTools
  private

    def blank_string_attributes_to_nil
      self.attributes.each do |attr_name, attr_value|
        self.send("#{attr_name}=", nil) if attr_value.kind_of?(String) && attr_value == ''
      end
    end
end

Then you have to add these lines into each of your app/models/* files :

require Rails.root.to_s + '/lib/my_model_tools.rb'

class MyExampleModel < ActiveRecord::Base

  include MyModelTools
  before_validation :blank_string_attributes_to_nil

  ...

end

This will convert any empty string attributes into a NIL value to be store into your DB (for the models where you copy the lines above).

So you won't have to assign each attribute by hand to NIL when they are empty string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.