我一直在通过
started.html。
我在控制器中执行保存数据时遇到了一个错误。运行博客时出现的错误是:-未定义的方法“`title”表示为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中定义了标题时,请帮我找出为什么会出现这个错误。
发布于 2013-08-01 11:23:05
在private之后定义的所有方法只能在内部访问。将show方法移动到private之上。并确保您有一个名为app/view/post/show.html.erb的文件,而不是.rb。
祝好运!
发布于 2014-01-17 05:13:10
# 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
https://stackoverflow.com/questions/17965341
复制相似问题