Search code examples
activerecordruby-on-rails-3arel

Why ARel query is returned as ActiveRecord::Relation class instead of parent class?


I have a class:

class Technician < ActiveRecord::Base  
  scope :named, lambda {|name| where(["first_name LIKE ?", "%#{name}%"])}  
end  

In rails console, when I do the following query:

technician = Technician.named("john")  
technician.class => ActiveRecord::Relation and not Technician  

this matters because I get a no method error when I try to access the class attributes:

technician.id => no method error  

what am I doing wrong?


Solution

  • Arel returns ActiveRecord::Relation so that it can defer the execution to the last moment and provide better composability.

    Technician.named("john").first instead of Technician.named("john") to get the technician.