NoMethodError in messages # show;

I studied rails through

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

I encountered an error while performing data save in the controller. Error that occurs when starting a blog: - undefined `title 'method for nil: NilClass

**

My code for 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 

**

My code for show.html.rb

**

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

**

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 why this error occurs when I defined the name in create_posts.

+3
source share
2 answers

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

Good luck

+15
source
 # 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

0
source

Source: https://habr.com/ru/post/955327/


All Articles