Posts#show 中没有方法错误; [英] NoMethodError in Posts#show ;

查看:39
本文介绍了Posts#show 中没有方法错误;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习 Rails

i have been learning rails through

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

我在控制器中执行保存数据时遇到错误.运行博客时出现的错误是:-undefined method `title' for nil:NilClass

I came across a error while performing save data in controller. The error that comes up when running the blog is :-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 代码是

My code for show.html.rb is

**

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

**

create_posts.rb 的代码

The code for 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 中定义标题时出现此错误的原因.

Please help me out why this error is coming up when I have defined title in create_posts.

推荐答案

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

All methods defined after private are accessible only internally. Move the show method above private. And make sure you have a file called app/views/posts/show.html.erb and not .rb

祝你好运!

这篇关于Posts#show 中没有方法错误;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆