Rails: Dynamic Finders

 

 

Rails's ActiveRecord can use a dymatic way to finder

Like this model class in rails:

class Article < ActiveRecord::Base
  attr_accessible :body, :excerpt, :location, :published_at, :title
  validates :title, :presence => true
  validates :body, :presence => true
end

It don't have much query function, but you can use query function like:

Article.find_by_title('Hello')
=>; #<;article id:1,="" title:="" "hello",="" ...="">;

It because it use Ruby’s method_missing functionality to automatically create methods that don’t exist until runtime. Using dynamic finders, you can include the attribute you’re looking for directly in the method name.

There are several variations of dynamic finders, which are summarized in the Table:

 
Finder Example
find_by_*(cond) find_by_title('Hello') #=>; Article
find_all_by_*(cond) find_all_by_title('Hello') #=>; Array
find_by_*_and_*(cond1, cond2) find_by_title_and_published_on('Hello', '2012-03-12') #=>;Articlelike creating a record. You can update attributes one at a time and
then save the result, or you can update attributes in one fell swoop. When you update a
record, a SQL UPDATE statement is constructed behind the scenes. First, you use a find
operation to retrieve the record you
find_all_by_*_and_*(cond1, cond2) find_all_by_title_and_published_on('Hello', '2012-03-12') #=>;Array

Amazing...