简体   繁体   English

ActiveModel :: ForbiddenAttributesError为什么Rails会忽略Strong_params?

[英]ActiveModel::ForbiddenAttributesError why Rails ignore Strong_params?

class PostsController < ApplicationController

    def new
    end

    def create 
        @post = Post.new(params[:post])
        @post.save
        redirect_to @post
    end

    private

    def post_params
      params.require(:post).permit(:title, :text)
    end

    def show
       @post = Post.find(params[:id])
    end

    def index
    @posts=Post.all
    end
end

Because you're not using it. 因为您没有使用它。

Replace params[:post] with your method post_params . 用您的方法post_params替换params[:post]

You'll need to improve your code (you've set your index and show methods as private!): 您需要改进代码(您已经设置了index并将方法show为私有!):

class PostsController < ApplicationController

    def new
        @post = Post.new
    end

    def create 
        @post = Post.new(post_params)
        @post.save
        redirect_to @post
    end

    def show
       @post = Post.find(params[:id])
    end

    def index
       @posts=Post.all
    end

    private

    def post_params
      params.require(:post).permit(:title, :text)
    end
end

As per the strong params documenation , you need to call the private method with your strong params inside in order to pass them 根据强参数文档 ,您需要在内部带有强参数的情况下调用私有方法,以便传递它们

Make post_params method as private method but not other method 将post_params方法设置为私有方法,而不是其他方法

private

def post_params
  params.require(:post).permit(:title, :text)
end

Call it where you want to use like this. 像这样在需要使用的地方调用它。

def create 
    @post = Post.new(post_params)
    @post.save
    redirect_to @post
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM