0

i have come across problem in adding links to posts. My code for index is :-

<h1>Listing posts</h1>
<%= link_to 'new post',new_post_path %>
<table>
<tr>
<th>title </th>
<th>text</th>
</tr>
<% @posts.each do |post| %>
<tr>
<td> <%= post.title %> </td>
<td><%= post.text %> </td>
</tr>
<% end %>
</table>
<h1> hello rails </h1>
<%= link_to "my blog",controller: "posts" %>
<p>Find me in app/views/welcome/index.html.erb</p>

my code for post_controller is:-

class PostsController < ApplicationController
def index
@posts=post.all
end
def new
end
def create
@post=Post.new(params[:post].permit(:title,:text))
@post.save
redirect_to @post
#render text: params[:post].inspect
end
def show
@post=Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title,:text)
end
end

The error that is shown is "undefined local variable or method `post' for #" Please help me out to trace the error

neha sharma
  • 117
  • 1
  • 3
  • 11

1 Answers1

1

Check your code of method index in PostsController:

It should be:

def index
@posts=Post.all
end

Instead of:

def index
@posts=post.all
end

Check:

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

This doc clearly says:

Open app/controllers/posts_controller.rb and inside the PostsController class, define a new method like this:

def new
end

With the new method defined in PostsController, if you refresh you'll see another error:

Template is missing.

You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails errors out.

Read the document to understand and try to resolve it yourself by associating some view to the method. Its too easy, the rails way.

sjain
  • 23,126
  • 28
  • 107
  • 185