[Chartjs]-How can I replace null value with n/a in ruby on rails?

1πŸ‘

I think you can do this at many levels, so depends on what you need.
One way to solve this would be to set a default value in the database. So every time your model is saved with null it will actually be saved as "n\a".

You can run a migration like so:

change_column_default :rosters, :caste_group, "n\a"

But maybe you don’t want to edit all the data in the DB. In that case, you can do it at the model or presenter level. I think the code you posted from the helper is all right. Are you not satisfied with it?

1πŸ‘

If your query can return null, and "", e.g

Roster.group(:caste_group).count
{
  nil=>12,
  ''=>123,
  'name_first'=>2
}

This can help

sql = <<-SQL
  SELECT
    CASE
    WHEN caste_group IS NULL
    THEN 'n/a'
    WHEN caste_group=''
    THEN 'n/a'
    ELSE caste_group
    END AS caste_group,
    count(*)
  FROM rosters
  GROUP BY 1
SQL
result = ActiveRecord::Base.connection.execute(sql).to_a

This will compile NULL or ” to β€˜n/a’.

example result:

[
  {"caste_group"=>"n/a", "count"=>"1"},
  {"caste_group"=>"name_first", "count"=>"2"}
]

Next you can transform this in needed hash.

result.each_with_object({}) { |caste_group, res| res[caste_group['caste_group']] = caste_group['count'] }

e.g

{"n/a"=>"1", "name_first"=>"2"}

0πŸ‘

I thankfully solves this.
The problem with mine is that I have already updated the database to "n/a". So, when I change the key through transform_keys I am facing the problem.
After that I rename n/a to "N/A" and solves for me.

   caste_group = Roster.group(:caste_group).count
@caste_group = caste_group.transform_keys{ |key| key==""? "N/A":key }

I am posting the answer because it might be helpful for others in future.

Leave a comment