how to permit an array with strong parameters

前端 未结 5 434
说谎
说谎 2020-11-22 13:50

I have a functioning Rails 3 app that uses has_many :through associations which is not, as I remake it as a Rails 4 app, letting me save ids from the associated model in the

相关标签:
5条回答
  • 2020-11-22 14:19

    If you want to permit an array of hashes(or an array of objects from the perspective of JSON)

    params.permit(:foo, array: [:key1, :key2])
    

    2 points to notice here:

    1. array should be the last argument of the permit method.
    2. you should specify keys of the hash in the array, otherwise you will get an error Unpermitted parameter: array, which is very difficult to debug in this case.
    0 讨论(0)
  • 2020-11-22 14:22

    It should be like

    params.permit(:id => [])
    

    Also since rails version 4+ you can use:

    params.permit(id: [])
    
    0 讨论(0)
  • 2020-11-22 14:37

    I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:

    filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]
    

    This works:

    params.require(:model).permit(filters: [[:name, values: []]])
    
    0 讨论(0)
  • 2020-11-22 14:40

    If you have a hash structure like this:

    Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}
    

    Then this is how I got it to work:

    params.require(:link).permit(:title, time_span: [[:start, :end]])
    
    0 讨论(0)
  • 2020-11-22 14:42

    This https://github.com/rails/strong_parameters seems like the relevant section of the docs:

    The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

    To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

    params.permit(:id => [])
    

    In my app, the category_ids are passed to the create action in an array

    "category_ids"=>["", "2"],
    

    Therefore, when declaring strong parameters, I explicitly set category_ids to be an array

    params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])
    

    Works perfectly now!

    (IMPORTANT: As @Lenart notes in the comments, the array declarations must be at the end of the attributes list, otherwise you'll get a syntax error.)

    0 讨论(0)
提交回复
热议问题