NoMethodError in Posts#show ;

ぐ巨炮叔叔 提交于 2019-12-05 02:29:38

问题


i have been learning rails through

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

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

**

My code for posts_controller.rb is

**

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

**

My code for show.html.rb is

**

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

**

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

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


回答1:


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

Good luck!




回答2:


# 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/nomethoderror-in-postsshow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!