Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable strong parameters for a specific action

I have a serious problem with strong parameters. Its working pretty well in my about 200 actions but in one it doesn't because I'm working very dynamic with the parameters there and I also cant change it because of the applications design.

So I want to disable strong parameters validation in just this specific action. Is there a way to do this?

like image 992
davidb Avatar asked May 28 '15 14:05

davidb


People also ask

What are strong parameters?

Strong Parameters, aka Strong Params, are used in many Rails applications to increase the security of data sent through forms. Strong Params allow developers to specify in the controller which parameters are accepted and used.

What is permit in Ruby on Rails?

It returns an instance of ActionController::Parameters for the key passed into require . The permit method returns a copy of the parameters object, returning only the permitted keys and values. When creating a new ActiveRecord model, only the permitted attributes are passed into the model.

What does require do in Rails?

require can also be used to load only a part of a gem, like an extension to it. Then it is of course required where the configuration is. You might be concerned if you work in a multi-threaded environment, as they are some problems with that. You must then ensure everything is loaded before having your threads running.


2 Answers

Strong parameters overrides the params method in ActionController::Base. You can simply override it and set it back to what you want yourself.

So this:

class MyController < ApplicationController
  def params
    request.parameters
  end
end

Will effectively disable strong parameters for all actions in your controller. You only wanted to disable it for a particular action though so you could do that with:

class MyController < ApplicationController
  before_action :use_unsafe_params, only: [:particular_action]

  def params
    @_dangerous_params || super
  end

  def particular_action
    # My params is unsafe
  end

  def normal_action
    # my params is safe
  end

  private

  def use_unsafe_params
    @_dangerous_params = request.parameters
  end
end
like image 142
Ritchie Avatar answered Oct 07 '22 06:10

Ritchie


Not too sure if this is best practice but for Rails 5 I just use request.params instead of params anytime I want to skip strong params.

So instead of something like:

post = Post.new(params[:post])

I use:

post = Post.new(request.params[:post])
like image 33
Sajad Torkamani Avatar answered Oct 07 '22 05:10

Sajad Torkamani