首页 > 解决方案 > 数据库查询在控制台中没有错误,但在控制器类中

问题描述

我的控制器中有这段代码,它应该给我一个特定类别的最后更新的帖子。

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"

标签: ruby-on-rails

解决方案


它不起作用,并给了我一个 nil:class 的帖子。但它在命令行的 Rails 控制台中运行良好。

您的方法的问题是它category_paramnil或者没有特定的记录category_param导致nil post。确保category_param不是nil并且是现有类别,以便查询将返回一条记录。

或者

你可以重写这一行

@last_post_title = post.title 

作为

@last_post_title = post.title if post

避免错误


推荐阅读