简体   繁体   中英

Rails Nested strong parameters, how to use them?

i am using Jquery dataTables. This library is operating on specific json structure like:

{"data"=>{"209"=>{"order"=>"", "name"=>"dssdbs", "task_deadline"=>"", "task_status"=>"Nie przypisano", "board_id"=>"17", "user_id"=>"2", "task_group"=>"WWW", "assigned-many-count"=>"0"}}, "id"=>"209"}

And the question is, how can i change it into strong parameters? For now i am operating on my params in controller in very bad way:

task_params = params[:data][params[:id]]
@task = Test.find(params[:id]
@task.order = task_params[:order]
@task.name = task_params[:name]
@task.task_deadline = task_params[:deadline]
@task.task_status = task_params[:task_status]
@task.board_id = task_params[:board_id]
@task.user_id = task_params[:user_id]
@task.task_group = task_params[:task_group]
@task.save

When i want to add new task, my params looks like:

{"data"=>{"0"=>{"order"=>"", "name"=>"dssdbs", "task_deadline"=>"", "task_status"=>"Nie przypisano", "board_id"=>"17", "user_id"=>"2", "task_group"=>"WWW", "assigned-many-count"=>"0"}}}

As you see i am using 0 instead of ID.

Is there some clean and nice way to use strong parameters here? Everything works fine but it's completely different from DRY methodology.

Thank you for any advise

def task_params 
  params.fetch(:data)
        .fetch(params[:id])
        .permit(
          :name,
          :order
          # ...
        )
end

fetch can be replaced with require if you want the code to raise if the parameter is missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM