Ruby on rails 4 attr_accessible

时间:2014-03-23 22:54:09

标签: ruby-on-rails

我正在尝试访问数据库并输入一些信息。它给了我一个错误说"未定义的局部变量或方法`post_params'对于#< PostsController:0x00000005aad728>"

我知道这已被回答here。 但是我试着跟着他们做了什么,它只是不起作用,有人可以帮助我吗?

class PostsController < ApplicationController
  def index
     @post = Post.all     
  end

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

  def new
      @post = Post.new
  end

  def create
      @post = Post.new(post_params)

      if @post.save
          redirect_to posts_path, :notice => "Your post was saved"
      else
          render ="new"
      end

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

2 个答案:

答案 0 :(得分:4)

您的end create方法附带了private关键字和post_params方法。将其更新为:

def create
      @post = Post.new(post_params)

      if @post.save
          redirect_to posts_path, :notice => "Your post was saved"
      else
          render ="new"
      end
end # Add end here

private
def post_params
     params.require(:post).permit(:title, :content)
end
end # Remove this end

答案 1 :(得分:1)

您可以在create方法中定义post_params方法。把它移到它外面,一切都会起作用。