1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Although this works fine, I use @player_types in my view to display errors.full_messages(). Doing this way @player_types does not retain any error information that would have occured while assigning

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.