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?)
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?})
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With