Search code examples
deviseruby-on-rails-4has-and-belongs-to-manystrong-parameters

unpermitted parameter in has and belongs to many association


I'm trying to create a rails 4 app with a user model and an Industry model. They have a has_and_belongs_to_many association between both of them. I created the join table as per the guides http://guides.rubyonrails.org/association_basics.html I'm getting upermitted parameter for :industry_ids. So I followed the devise section on strong parameters

class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :about
    devise_parameter_sanitizer.for(:sign_up) << :industry_ids
  end
end

But as I read here http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html, for an association like this I need to tell rails that this is an array.

How do I fix the creation of users with an :industries association?


Solution

  • I ended up using a block.

    class ApplicationController < ActionController::Base
      before_filter :configure_permitted_parameters, if: :devise_controller?
    
      # Prevent CSRF attacks by raising an exception.
      # For APIs, you may want to use :null_session instead.
      protect_from_forgery with: :exception
    
      protected
    
      def configure_permitted_parameters
        devise_parameter_sanitizer.for(:sign_up) { |u|
          u.permit(:email, :password, :password_confirmation,
                   :about, industry_ids: []) }
      end
    end