ActiveModel::ForbiddenAttributesError + cancan + rails 4 + model with scoped controller

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 13:44:26

Using name spaces. Please try to change your code to this one below. I had same issue after @JiriKolarik suggested his solution to work with name spaces. I hope it helps.

  before_filter do
    resource = controller_name.singularize.to_sym
    method = "#{resource}_params"
    params[resource] &&= send(method) if respond_to?(method, true)
  end

if you use this workflow

before_filter do
  resource = controller_path.singularize.gsub('/', '_').to_sym
  method = "#{resource}_params"
  params[resource] &&= send(method) if respond_to?(method, true)
end

then your params method should look like this

  def admin_app_params
    params.require(:admin_app).permit(:name, :description, :author, :url_path, :validated, :active, :version)
  end

The reason why, it's because form generators (form_form, simple_form) generate params with namespace_resource

So if you have Blog::Post, form generator will create params like this

{ "blog_post"=>{"title"=>"Post"}, "commit"=>"Create", "action"=>"create", "controller"=>"blog/posts", "locale"=>"en"}

And this is how before filter works:

before_filter do
  resource = controller_path.singularize.gsub('/', '_').to_sym # => 'blog/posts' => 'blog/post' => 'blog_post' => :blog_post
  method = "#{resource}_params" # => 'blog_post_params'
  params[resource] &&= send(method) if respond_to?(method, true) # => params[:blog_post]
end

If you need read :blog_post from params, solution above will not work. If you need read :post from params, then this solution will not work, if your controller will be blog/post

cancan just does not work with the strong parameter. While there is a new gem cancancan which works well without any code change.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!