帖子中的NoMethodError#show;

时间:2013-07-31 08:31:32

标签: rails-migrations

我一直在学习通过

学习

http://guides.rubyonrails.org/getting_started.html

我在控制器中执行保存数据时遇到错误。运行博客时出现的错误是: - nil的未定义方法`title':NilClass

**

  

我对posts_controller.rb的代码是

**

class PostsController < ApplicationController
def new
end
def create
@post=Post.new(params[:post].permit(:title,:text))
@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
end

**

我的show.html.rb代码是

**

<p>
<strong> Title:</strong>
<%= @post.title %>
</p>
<p>
<strong> Text:</strong>
<%= @post.text %>
</p>

**

  

create_posts.rb的代码

**

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.text :text

      t.timestamps
    end
end

当我在create_posts中定义了标题时,请帮我解释为什么会出现此错误。

2 个答案:

答案 0 :(得分:15)

private之后定义的所有方法只能在内部访问。将show方法移到private上方。并确保您有一个名为app / views / posts / show.html.erb的文件,而不是.rb

祝你好运!

答案 1 :(得分:0)

# Make sure that you trying to access show method before the declaration of private as we can't access private methods outside of the class.

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


def index
  @posts = Post.all
end

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

  if @post.update(params[:post].permit(:title, :text))
    redirect_to @post
  else
    render 'edit'
  end
end

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

// vKj