abh*_*9yu 8 activerecord ruby-on-rails ruby-on-rails-4
我正在使用Rails 4.2.3和ruby 2.2.1
我在角色模型中写了一个范围如下:
应用程序/模型/ role.rb
scope :default, -> { find_by(default: true) }
Run Code Online (Sandbox Code Playgroud)
现在我跑的时候
> Role.default
#this is the output I got.
Role Load (0.1ms) SELECT `roles`.* FROM `roles` WHERE `roles`.`default` = 1 LIMIT 1
Role Load (0.1ms) SELECT `roles`.* FROM `roles`
=> []
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这会触发2个查询并返回错误的结果.
我尝试使用类方法而不是范围
def self.default
self.find_by(default: true)
end
Run Code Online (Sandbox Code Playgroud)
现在我跑的时候
Role.default
#this is the output I got
Role Load (0.2ms) SELECT `roles`.* FROM `roles` WHERE `roles`.`default` = 1 LIMIT 1
=> nil
Run Code Online (Sandbox Code Playgroud)
使用类方法,find_by正常工作.
我无法理解我在这里做错了什么.任何帮助,将不胜感激.提前致谢.
| 归档时间: |
|
| 查看次数: |
3042 次 |
| 最近记录: |