how to permit an array with strong parameters

前端 未结 5 491
说谎
说谎 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: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.)

提交回复
热议问题