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

时间:2014-03-16 12:14:47

标签: ruby-on-rails

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

3 个答案:

答案 0 :(得分:1)

因为你没有使用它。

params[:post]替换为您的方法post_params

答案 1 :(得分:1)

您需要改进代码(您已将indexshow方法设置为私有!):

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

根据strong params documenation,您需要使用内部强大的params调用私有方法以传递它们

答案 2 :(得分:0)

将post_params方法设为私有方法,而不是其他方法

private

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

将其称为您想要使用的地方。

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