我的控制器中有此代码,该代码应为我提供特定类别中的最新更新帖子。
def set_subcategory_meta_data(category_param)
post = Post.where("category = ?", category_param).order("updated_at").last
@last_post_title = post.title
@last_post_user_name = 'JohnDoe20181827'
@last_post_update_time = '(25.08.2018, 16:08)'
@post_count = Post.where("category = ?", category_param).count
@comment_count = 999
@last_post_path = user_path(User.first)
@last_post_user_path = user_path(User.last)
end
它不起作用,给了我nil:class的帖子。但是它在命令行的Rails控制台中工作得很好。
我不知道我在这里做错了什么...
irb(main):010:0> post.title="hey he euy"
=> "hey he euy"
irb(main):011:0> post.save
(0.0ms) BEGIN
User Load (2.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 64], ["LIMIT", 1]]
Post Exists (0.0ms) SELECT 1 AS one FROM "posts" WHERE LOWER("posts"."title") = LOWER($1) AND "posts"."id" != $2 LIMIT $3 [["title", "hey he euy"], ["id", 1], ["LIMIT", 1]]
Post Update (1.0ms) UPDATE "posts" SET "title" = $1, "updated_at" = $2 WHERE "posts"."id" = $3 [["title", "hey he euy"], ["updated_at", "2018-09-11 15:49:43.758079"], ["id", 1]]
(1.0ms) COMMIT
=> true
irb(main):012:0> Post.where("category = ?", "ruby-on-rails/developers").order("updated_at").last.title
Post Load (0.0ms) SELECT "posts".* FROM "posts" WHERE (category = 'ruby-on-rails/developers') ORDER BY updated_at DESC LIMIT $1 [["LIMIT", 1]]
=> "hey he euy"
答案 0 :(得分:0)
它不起作用,给了我nil:class的帖子。但是它只是有效 在命令行的Rails控制台中可以正常运行。
您的方法存在的问题是category_param
为 nil 或没有记录与特定的category_param
一起导致 nil post 。确保category_param
为 nil 且不存在现有类别,以便查询将返回记录。
OR
您可以重写此行
@last_post_title = post.title
为
@last_post_title = post.title if post
避免错误