简体   繁体   中英

How to permit hash with * key => values?

I want to create an object with strong params that can accept dynamic hash keys.

This is my code,

Quiz.create(quiz_params)


def quiz_params
  params.require(:quiz).permit(:user_id, :percent, :grade, questions: {})
end

data that gets passed in would look something like this.

// the keys that get passed into question is always different

quiz: {
  user_id: 1,
  percent: 80,
  grade: "B",
  questions: {
    "12": "24",
    "1": "12",
    "4": "3",
    "5": "22"
  }
}

Currently however, when I try to create a Quiz, the questions hash turns out empty.

In rails 5.1.2, the original syntax of passing an empty hash for questions should work:

def quiz_params
  params.require(:quiz).permit(:user_id, :percent, :grade, questions: {})
end

See https://github.com/rails/rails/commit/e86524c0c5a26ceec92895c830d1355ae47a7034

Until now I have only seen this:

def quiz_params
  questions_params = (params[:quiz] || {})[:questions].keys
  params.require(:quiz).permit(:user_id, :percent, :grade, questions: questions_params)
end

Have you considered changing your api instead?

quiz: {
  user_id: 1,
  percent: 80,
  grade: "B",
  answers_attributes: [
    {
      question_id: "12"
      value: "24"
    }, 
    {
      question_id: "3"
      value: "12"
    }
    # ...
  ]
}

This is how both form_for and nested_attributes work. Instead of giving yourself a potential mass injection vulnerability - rethink your domain modeling. You can do better.

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