Is rails 4 find_by deprecated?

僤鯓⒐⒋嵵緔 提交于 2020-02-21 10:36:06

问题


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.:

before:

Model.find_by_username 'username'

after: --in model---

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

is it a good naming? what names do you give for such methods?

Update:

find_by is not deprecated but the announcement could have been clearer!


回答1:


According to the Rails 4 Release Notes:

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

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.

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)


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_... 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!(...).



回答2:


I would avoid cluttering your model with such methods. Also, Rails still provides the find_by method. Thus I think a better solution would be

Model.find_by(username: 'whatever_username')



回答3:


It was deprecated in favour of

Model.find_by username: 'username'

so you should probably use this version.



来源:https://stackoverflow.com/questions/23921780/is-rails-4-find-by-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!