简体   繁体   中英

Why can't I display single post in Ruby on Rails?

I'm learning Ruby on Rails and I have problem with display single post by id in view.

@post = Post.find(params[:id])

That's the way I'm passing varible to the view.

<h1><%= @post.title %></h1>

And this is how I try to display varible. The interesting thing is that when I'm trying to display all posts then that is works.

What can be wrong ?

[update with logs]

Started GET "/posts/2" for 127.0.0.1 at 2015-10-31 18:15:43 +0100
Processing by PostsController#show as HTML
  Parameters: {"id"=>"2"}
  Post Load (0.2ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", "2"]]
  Rendered posts/show.erb within layouts/application (0.3ms)
Completed 200 OK in 6ms (Views: 3.8ms | ActiveRecord: 0.2ms)
[2015-10-31 18:15:43] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Would be easy to debug:

  1. add gem 'pry' to your Gemfile
  2. bundle install
  3. Add to your view

binding.pry

@post.title

At the prompt in your server log do @post or if it never hits this you are rendering the wrong view, or etc...

Since you're new, here's how your controller and views should look:

#config/routes.rb
resources :posts

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   def show
      @post = Post.find params[:id]
   end
end

#app/views/posts/show.html.erb
<%= @post.title %>

This is what you need to have to get this working.

If you do as above, and have the relative Post object in the database, it should work for you.

If it does not, it suggests a problem somewhere else. A good test would be to use the Rails console :

$ rails c
$ post = Post.find params[:id]
$ post.title #-> will output post's title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM