Rails 4 is getting rid of dynamic finders, so

User.find_by_hash(hash)

becomes

User.where(hash: hash) # .first

Okay, not a big deal. But what is the best way to deal do with dynamic bang finders like User.find_by_hash!(hash) since there is no where!() method? Rails 4 Release Notes conveniently avoid this.

Update: It plainly says: "All dynamic methods EXCEPT for find_by_... and find_by_...! are deprecated."

Either the pages has changed since or I was blind when reading it.

有帮助吗?

解决方案 3

It plainly says: "All dynamic methods EXCEPT for find_by_... and find_by_...! are deprecated."

其他提示

I think the new syntax is

User.find_by!(hash: hash)

At least that's how ryanb does it: http://railscasts.com/episodes/400-what-s-new-in-rails-4

Hope that helps.

Well, if you need a method that finds all but raises exception if the relation is empty, you can create such new method for your models yourself (or mixin to ActiveRecord::QueryMethods). Something like:

def where!(*args)
  rel = where(*args) 
  raise RecordNotFound if rel.empty?
  rel
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top