首页 > 解决方案 > Rails 5.2:如果 current_user 与 current_user.present 的区别?在视图中

问题描述

我关注这个帖子。在我看来:

- if current_user
- if current_user.present?
- if current_user.exists?
- if current_user.any?

我得到错误:

undefined method `exists?' for #<User:0x00007fd68f4067b8>
undefined method `any?' for #<User:0x00007fd68f4067b8>

所以只有前两个工作。为什么?性能是否有任何差异:

- if current_user
vs
- if current_user.present?

- if current_user.name
vs
- if current_user.name.present?

标签: ruby-on-railsrails-activerecord

解决方案


当你调用对象的方法时,你必须知道你在做什么。

current_user.present?

在这里,您调用present?对象上调用的方法current_user。这是有效的,因为方法present?是在这个对象上定义的。当你这样做

current_user.exists?

您期望current_user响应一个名为exists?. 但它没有,因此错误。

您在这个问题中混杂了一些东西。

仅当您确定它响应此方法时才调用对象上的方法。

if current_uservs之间的区别if current_user.present?是对对象真实性的隐式与显式检查。看,在 Ruby 中,除了falseand之外的一切nil都是真实的。所以if current_user意味着 ifcurrent_user是除了nilor falsethen 继续的任何东西。您依赖于表达式评估,而在current_user.present?您显式地依赖于方法调用 ( present?) 的返回值。

我建议你

  • 总是用明确的,因为它读起来更好;
  • 阅读 Ruby 中的对象和方法。

推荐阅读