ruby-on-rails - 数据库查询在控制台中没有错误,但在控制器类中
问题描述
我的控制器中有这段代码,它应该给我一个特定类别的最后更新的帖子。
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"
解决方案
它不起作用,并给了我一个 nil:class 的帖子。但它在命令行的 Rails 控制台中运行良好。
您的方法的问题是它category_param
是nil或者没有特定的记录category_param
导致nil post。确保category_param
不是nil并且是现有类别,以便查询将返回一条记录。
或者
你可以重写这一行
@last_post_title = post.title
作为
@last_post_title = post.title if post
避免错误
推荐阅读
- xml - 从 xml 树迭代器返回结果
- c++11 - 相对变换的迭代乘法导致快速不稳定性
- xml - 如何将时间从 UTC 转换为 pom.xml 中的本地时间?
- javascript - 用于 App.vue 的 Main.js 调用 API 来填充值
- javascript - 如何将一个输入框中的值复制到另一个输入框中?
- node.js - 我应该在哪里存储 code_verifier(使用 PKCE 的 oauth 2.0 代码授权流程)
- r - 循环遍历具有相同前缀的行和变量
- java - JoptionPane 关闭而不做任何事情
- kubernetes - kubernetes 持久卷声明,大小不受限制
- c - TLB、CPUID 和大页面?