Roman Roman -4 years ago 93
Ruby Question

Overwrite permited_params if rails controller has been inherited

Here an example:

class Base<ApplicationController
private

def permited_params
params.require(:object_name).permit(:name, :description)
end
end

class Post<Base
private

def permited_params
params.require(:post).permit(:name, :description, :owner)
end
end


I'm getting an error ActiveModel::ForbiddenAttributesError when call action create. How I can overwrite this permited_params

Answer Source

Params, in general, have a good reason to exist and make sure that not everything can be saved into your database. However, if you want to permit all params you can call

params.require(:post).permit! 

In case you just want to change the params you can change the attribute names.

params.require(:post).permit(:name, :description, :some_you_want, some_more ) etc. 

In general, you should add all params you want to save into the list of permitted params. So you make sure that all the attributes you want to save will be stored and no more. You can have permitted_params in every controller. You do not need to call it permitted params. For instance you can call it like this in your posts_controller:

def create
  @post = Post.new(post_params)
  #.... your code
end

private 
def post_params 
  params.require(:post).permit(:name, :description, :owner)
end

This also works for inherited controllers.

Instead of params.require(:post).permit(... you can use whatever params you want, like params.require(:reply).permit(... The required param will throw an error if it is not available. So you need to make sure it exists for example by

@post = Post.new 

Other params are optional and will not cause an error by default.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download