Updating nested hash parameters. Update action, ruby ​​on rails

I have a nested form containing a lesson / questions / answers. The user fills in the response fields and transmits messages. The hash is shown below:

Parameters: {"commit"=>"Submit Answers", "action"=>"update", "_method"=>"put", "authenticity_token"=>"y##########o=", "lesson"=>{"questions_attributes"=>{"0"=>{"id"=>"1", "answer"=>{"response"=>"answertextanswertext", "user_id"=>"2"}}, "1"=>{"id"=>"4", "answer"=>{"response"=>"answertextanswertext", "user_id"=>"2"}}}}, "id"=>"1", "controller"=>"lessons"}

In my upgrade instructions, I would like to skip the answers and overwrite user_id for security purposes. I changed the update instruction as follows:

  def update
    @lesson = Lesson.find(params[:id])
    lesson_params = params[:lesson]
    for q in lesson_params[:questions_attributes].values
      for s in q.values
        if !s[:user_id].nil?  
          s[:user_id] = current_user.id.to_s
        end
      end
    end
    if @lesson.update_attributes(lesson_params)
      flash[:notice] = "Answers submitted successfully."
      redirect_to lessons_path
    else
      render :action => 'edit'
    end
  end

I am noob, so intersecting the nested hash was a bit of trial and error. Is this a suitable way to scroll through a nested hash? Is this a good way to protect against mass misappropriation?

Thanks, Alex

+3
source share
1 answer

, - . , , . , ( ) . , , , , , , ( , , ).

, () q.values ​​- , . s [: user_id] [: lesson] [: question_attributes] [0] [: user_id] ( ).

" ", , , ?

0

Source: https://habr.com/ru/post/1772559/


All Articles