Home > Net >  How can I replace null value with n/a in ruby on rails?
How can I replace null value with n/a in ruby on rails?

Time:10-21

I am new here.Hope you will understand my problem. I am working on dynamic chart created through chartkick and chart.js in rails.

data shown from console that consits of null data.

The data got null is not the problem. The problem is that I want to display null/empty to n/a. My chart looks like To solve this I first update the database through the code mention below:

Roster.where(caste_group: "").update_all(caste_group:"n/a")

But this is exactly not what I wanted. Everytime updating the database is not efficient. Then I used transform key helper. The code goes as

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

Here Roster is the model which consist of following attribute caste_group as string and user select caste_group as dropdown. Using this transform key helper I got the result which doesn't display null value. null/empty value isn't rename to n/a. And my code in a view goes as

 = line_chart @event_chart,discrete:true, legend: "bottom",curve: false,
           colors: ["#67b55e","#d43766","#729be0"]

CodePudding user response:

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?

CodePudding user response:

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.

  • Related