ruby-on-rails - 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?
解决方案
当你调用对象的方法时,你必须知道你在做什么。
current_user.present?
在这里,您调用present?
对象上调用的方法current_user
。这是有效的,因为方法present?
是在这个对象上定义的。当你这样做
current_user.exists?
您期望current_user
响应一个名为exists?
. 但它没有,因此错误。
您在这个问题中混杂了一些东西。
仅当您确定它响应此方法时才调用对象上的方法。
if current_user
vs之间的区别if current_user.present?
是对对象真实性的隐式与显式检查。看,在 Ruby 中,除了false
and之外的一切nil
都是真实的。所以if current_user
意味着 ifcurrent_user
是除了nil
or false
then 继续的任何东西。您依赖于表达式评估,而在current_user.present?
您显式地依赖于方法调用 ( present?
) 的返回值。
我建议你
- 总是用明确的,因为它读起来更好;
- 阅读 Ruby 中的对象和方法。
推荐阅读
- c# - 编译期间的 Asp.net Web 应用程序错误
- python - 当我在python中使用ks测试时,为什么我的p值等于0而统计量等于1?
- r - Code equivalent to 'broom' icon in viewer pane of RStudio?
- python - 根据特定列组合两个数据框
- makefile - make -j 有和没有 sub make 的行为不同
- c# - Why would an HTML.Action cause the Home/Index method to be called repeatedly only when user is not authenticated?
- powershell - 根据组合框选定项设置文本框值
- c - 递归调用 C 中函数的隐式声明
- c - 解析字符串时,第一次迭代后缺少第一个字母
- c# - 使用 Unity:编写 Enemy AI 脚本 - 跟随玩家