Trancey
Trancey

Reputation: 709

assign_attributes and save later in loop - ruby rails

I want to assign_attribute to various rows in a table and then save them together in a loop. So here is how I am trying to do,

player_arr = []
params[:player_types].each do |index,p_type_params|
  if p_type_params[:id]
    player_arr << @player_types.find(p_type_params[:id]).assign_attributes(p_type_params)
  end
end

Later I wish to do a save atomically on all the updates as a transaction,

ActiveRecord::Base.transaction do
   player_arr.each do |p_type|
     p_type.save
   end
end

But this does not seem to work as p_type seems to be NilClass. I dont understand why because when I do player_arr.length I get a positive number. Also the goal here is to capture all the assignment errors in the first loop and then do an atomic save. Ofcourse I can save in the first loop itself but it will capture only the first encountered error. Any pointers will be really helpful

Upvotes: 1

Views: 458

Answers (1)

ihaztehcodez
ihaztehcodez

Reputation: 2133

The problem seems to be that you are doing too much in one line.

player_arr << @player_types.find(p_type_params[:id]).assign_attributes(p_type_params)

Here you are adding the return value of assign_attributes (nil) to the player_arr array.

Do this instead:

player_arr = []
params[:player_types].each do |index,p_type_params|
  if p_type_params[:id]
    player = @player_types.find(p_type_params[:id])
    player.assign_attributes(p_type_params)
    player_arr << player
  end
end

Upvotes: 1

Related Questions