在我的节目视图中获取未定义的方法'title'错误。这已经在其他帖子中发布并解决了几个,但看似其他问题而不是我的。
我还仔细检查过我可以通过rails控制台从数据库中读取,一切看起来都很好。
Loading development environment (Rails 4.2.3)
irb(main):001:0>
irb(main):002:0*
irb(main):003:0* post = Post.find(4)
Post Load (1.0ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMI
T 1 [["id", 4]]
=> #<Post id: 4, title: "Why Title Why", body: "Where is the Body??", category_i
d: nil, author_id: nil, created_at: "2015-08-12 14:49:38", updated_at: "2015-08-
12 14:49:38">
irb(main):004:0> post.title
=> "Why Title Why"
irb(main):005:0>
的routes.rb
Rails.application.routes.draw do
get 'categories/index'
get 'categories/edit'
get 'categories/new'
get 'categories/show'
get 'home/index'
resources :posts
resources :categories
root 'home#index'
的database.yml
default: &default
adapter: postgresql
username: postgres
password: aaaaa
pool: 5
timeout: 5000
development:
<<: *default
database: mysecondblog
Post_controller
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@posts = Post.find(params[:id])
end
def new
end
def create
end
def edit
end
def update
end
def destroy
end
private
def post_params
params.require(:post). permit( :title, :body, :category_id, :author_id)
end
end
帖子\ show.html.erb
<h1><%= @post.title %></h1>
<small><%= @post.created %></small>
<p><%= @post.body %></p>
感谢您的帮助
答案 0 :(得分:0)
你可以从视图中访问控制器内的@posts变量(@posts = Post.all)。
当你渲染视图文件(show.html.erb)时 - 你要求视图找到变量@post,参数.title,.created,.body - @posts in controller和@post in view - 不同的变量。< / p>
因此,您需要更改视图 show.html.erb
<h1><%= @posts.title %></h1>
<small><%= @posts.created_created %></small>
<p><%= @posts.body %></p>
或Controller内部的变量函数:
def index
@post = Post.all
end
def show
@post = Post.find(params[:id])
end