Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update attributes unless blank?

I have an existing Project record, and I'm importing a CSV file to update the associated Project attributes. However, often the CSV will contain blank fields and I don't want to overright exisiting attributes if the related CSV field is blank.

Something like this:

project.update_attributes(:name => row.field('project_name') unless row.field('project_name').blank?,                                             
                          :owner => row.field('project_owner') unless row.field('project_owner').blank?,
                          :due_date => row.field('project_due_date') unless row.field('project_due_date').blank?)
like image 338
Chap Avatar asked Oct 07 '09 11:10

Chap


3 Answers

project.update_attributes({:name => row.field('project_name'),                                                                         
                          :owner => row.field('project_owner'),
                          :due_date => row.field('project_due_date')}.reject{|k,v| v.blank?})
like image 135
gerrit Avatar answered Nov 15 '22 08:11

gerrit


You can do this from the controller if needed:

def some_params
    params.permit(:foo, :bar).reject { |_, v| v.blank? }
end

In this case the attributes won't be saved if they are blank

like image 20
Tomas Agrimbau Avatar answered Nov 15 '22 09:11

Tomas Agrimbau


This is an old question, but for the record, you can also set an attribute to nil (as opposed to blank) in order to exclude it from the updates list. I wouldn't call the following example best practice, but I think it can help clarify what's going on in the background: update_attributes will only attempt to update attributes that are provided in the hash, having a non-nil value.

params[:csv] = nil if params[:csv].blank? or (arbitrary other condition)
# now update like normal
if @project.update_attributes(project_params)
  ...
etc.
like image 43
Topher Hunt Avatar answered Nov 15 '22 10:11

Topher Hunt