Daniel Viglione
Daniel Viglione

Reputation: 9407

update only attributes that are not empty

I have a mass edit form. A user selects multiple existing records. And then clicks on a button which displays a new record form (all values are empty). User enters some data for each attribute and then clicks submit, which then updates all the selected records with the values specified.

The params hash submitted to the server looks like this:

{
  'lead_ids' => [2,4]
  'lead' => {
    'name' => 'donato',
    'email' => "",
    'phone' => ""
  }
}

So in this example, only the name attribute should be updated for lead with an id of 2 and 4.

This is what I came up with:

lead = Lead.new lead_params
leads = Lead.where(id: params[:lead_ids])
changed_attrs = lead_params.select {|param| !param.values.first.blank?}
leads.each do |lead|
  lead.update_attributes changed_attrs    
end

Is there a more Railsy way to do this?

Upvotes: 1

Views: 2191

Answers (1)

MTarantini
MTarantini

Reputation: 999

I would refactor the code into something a bit cleaner, like this:

leads = Lead.where(id: params[:lead_ids])
hash = lead_params.reject { |k, v| v.blank? }
leads.update_all(hash)

You search for the leads, remove the pairs with empty values, then update all the leads with that hash.

Could even make it a two-liner:

hash = lead_params.reject { |k, v| v.blank? }
Lead.where(id: params[:lead_ids]).update_all(hash)

Upvotes: 2

Related Questions