Problem in Saving an attribute as 0

Hi,

I need to save a field as 0 in a table

I have set the Default value as 0, for ‘number_of_days’ field in ‘tasks’
table.

I have a form which has this field.

When I set the field empty(blank field!) and save the form, it is saved
as null.

But I want this to be saved as 0.

I am using
<% remote_form_for(:task, :url => tasks_path) do |f| %>

and in ‘create’ method I save as @task.save

Note:
I have an idea of explicitly assigning zero
like…params[:task][:number_of_days]=0 if
params[:task][:number_of_days].blank?
But I want an alternative best approach without explicit assignment.

Thanks in advance…

Add this in your model:

before_save :set_field_to_zero_if_blank

def set_field_to_zero_if_blank
self.field = 0 if self.field.blank?
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs