pvdhpl
pvdhpl

Reputation: 53

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

Upvotes: 0

Views: 24

Answers (1)

max
max

Reputation: 102368

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.

Upvotes: 1

Related Questions