views:

223

answers:

2

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?)
A: 
attrs = [:name,:owner,:due_date].inject({}) {|res,obj| res[obj] = row.field("project_#{obj}") unless row.field("project_#{obj}").blank? }
project.update_attributes attrs
khelll
Not very easily readable ;(
Damien MATHIEU
Agreed, compared to the picked solution.
khelll
+8  A: 
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?})
gerrit