Rails 4 find_by是否已弃用? [英] Is rails 4 find_by deprecated?

查看:77
本文介绍了Rails 4 find_by是否已弃用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说find_by已过时,这是真的吗?我一直在考虑其他选择,例如为每个查找创建一个不同的方法,例如:

I heard that find_by is deprecated is this true? I have been thinking of alternatives such as creating for each find a different method, e.g.:

之前: p>

before:

Model.find_by_username 'username'

之后:
-在模型中---

after: --in model---

class << self
   def by_username username
      where(:username => username).first 
   end
end

这是一个好名字吗?

find_by尚未被弃用,但声明可能更清晰了!

推荐答案

根据路轨4发行说明


所有 dynamic 方法,但find_by _...和find_by _...除外。 !已弃用。

All dynamic methods except for find_by_... and find_by_...! are deprecated.

find_by 不是动态方法,因此 find_by _... & find_by _...!是动态的,但如上所述仍未弃用。

find_by is not a dynamic method and therefore it's NOT DEPRECATED, and find_by_... & find_by_...! are dynamic, but still not deprecated as mentioned above.

因此,您仍然可以使用Active Record提供的原始方法,而不必定义自己的方法:

So that means you still can use the original methods provided by Active Record without having to define your own:

Model.find_by_username(:username)
Model.find_by(username: 'value', age: 24)



如果您想要真正不推荐使用的查找器方法的功能,则可以包括将其移入的宝石: activerecord -deprecated_finders 。或遵循Rails 4发行说明中所述:


If you want the functionality of the really deprecated finder methods you can either include the gem that they were moved into: activerecord-deprecated_finders. Or follow what the Rails 4 Release Notes say:


这里是您重写代码的方式:

Here's how you can rewrite the code:


  • find_all_by _...可以使用where(...)重写。

  • find_last_by _...可以使用where(..重写。 。)。last。

  • scoped_by _...可以使用where(...)进行重写。

  • find_or_initialize_by _...可以使用进行重写find_or_initialize_by(...)。

  • find_or_create_by _...可以使用find_or_create_by(...)重写。

  • find_or_create_by _... !!可以使用find_or_create_by!(...)进行重写。

  • find_all_by_... can be rewritten using where(...).
  • find_last_by_... can be rewritten using where(...).last.
  • scoped_by_... can be rewritten using where(...).
  • find_or_initialize_by_... can be rewritten using find_or_initialize_by(...).
  • find_or_create_by_... can be rewritten using find_or_create_by(...).
  • find_or_create_by_...! can be rewritten using find_or_create_by!(...).

这篇关于Rails 4 find_by是否已弃用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆