Class: TheGrid::Api::Command::BatchUpdate

Inherits:
TheGrid::Api::Command show all
Defined in:
lib/the_grid/api/command/batch_update.rb

Instance Method Summary collapse

Methods inherited from TheGrid::Api::Command

#batch?, build, #contextualize, #execute_on, find, register_lookup_scope, scopes

Instance Method Details

#configure(relation, params) ⇒ Object



3
4
5
6
7
8
# File 'lib/the_grid/api/command/batch_update.rb', line 3

def configure(relation, params)
  {}.tap do |o|
    o[:items] = params.fetch(:items, []).reject{ |item| item['id'].to_i <= 0 }
    raise ArgumentError, "There is nothing to update" if o[:items].blank?
  end
end

#run_on(relation, params) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/the_grid/api/command/batch_update.rb', line 10

def run_on(relation, params)
  record_ids = params[:items].map{ |row| row['id'] }
  primary_key = relation.scoped.table.primary_key
  records = relation.where(primary_key.in(record_ids)).index_by(&primary_key.name.to_sym)

  params[:items].map do |row|
    record = records[row['id'].to_i]
    record.tap{ |r| r.update_attributes(row.except('id')) } unless record.nil?
  end.compact
end