3

我一直在学习rails

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

在控制器中执行保存数据时遇到错误。运行博客时出现的错误是 :-undefined method `title' for nil: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 中定义标题时,请帮助我解决为什么会出现此错误。

4

2 回答 2

15

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

祝你好运!

于 2013-08-01T11:23:05.500 回答
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

于 2014-01-17T05:13:10.003 回答