strong parameters not accepting array

后端 未结 3 688
深忆病人
深忆病人 2021-01-02 00:51

I have this in my view which is a multiselect checkbox

Model

class User < ActiveRecord::Base
  has_many :user_roles, :dependent =         


        
相关标签:
3条回答
  • 2021-01-02 01:42

    See the Rails Strong Parameters documentation regarding nested attributes.

    The correct format is:

    params.permit(:name, {:roles => []}, ...)
    

    AnkitG's solution worked for me in Rails 4 using the Role Model gem for my user model. My user controller's implementation of _params ended up looking like:

    def user_params
      # Bug with permit for nested arrays... @see https://stackoverflow.com/a/17880288/2631472
      params.require(:user).permit(:first_name, :last_name, :middle_name).tap do |whitelisted|
        whitelisted[:roles] = params[:user][:roles]
      end
    end
    

    0 讨论(0)
  • 2021-01-02 01:48

    This should work

    params.require(:user).permit(:first_name, :role_ids => [])
    
    0 讨论(0)
  • 2021-01-02 01:52

    Answering myself, I got it working not directly, but the below method from the Strong Parameters issues discussion helped me in converting a normal parameter to a whitelisted one.

    def user_params
      params.require(:user).permit(:first_name).tap do |whitelisted|
        whitelisted[:role_ids] = params[:user][:role_ids]
      end
    end
    
    0 讨论(0)
提交回复
热议问题