2

I totally misunderstood a mechanism in rails... Imagine a product model that has many properties:

class Product < ActiveRecord::Base
    has_many :properties
end

Then, in console, I type:

p=Product.last #recover the last product created
arr=p.properties #return the properties in an Array
arr.class #return "Array", so it's effectively an Array object.

In Hirb it gives me:

1.9.3-p385 :161 > arr=p.properties
| id        | name        | presentation  | created_at              | updated_at              | value_type |
+-----------+-------------+---------------+-------------------------+-------------------------+------------+
| 905834907 | internet    | internet      | 2012-09-17 13:37:57 UTC | 2012-10-02 15:46:37 UTC | boolean    |
| 905834906 | three_d     | 3D            | 2012-09-17 13:37:47 UTC | 2012-10-10 13:10:07 UTC | boolean    |
| 161337574 | brand       | Marque        | 2012-05-22 14:13:04 UTC | 2013-03-26 16:12:12 UTC | string     |

etc...

Then, if I do:

1.9.3-p385 :162 > arr.where(:value_type => "boolean")
  Spree::Property Load (0.8ms)  SELECT "spree_properties".* FROM "spree_properties" INNER JOIN "spree_product_properties" ON "spree_properties"."id" = "spree_product_properties"."property_id" WHERE "spree_product_properties"."product_id" = 1060500665 AND "spree_properties"."value_type" = 'boolean'
+-----------+----------+--------------+-------------------------+-------------------------+------------+
| id        | name     | presentation | created_at              | updated_at              | value_type |
+-----------+----------+--------------+-------------------------+-------------------------+------------+
| 905834907 | internet | internet     | 2012-09-17 13:37:57 UTC | 2012-10-02 15:46:37 UTC | boolean    |
| 905834906 | three_d  | 3D           | 2012-09-17 13:37:47 UTC | 2012-10-10 13:10:07 UTC | boolean    |
| 905834914 | wifi     | wifi         | 2013-03-26 16:13:35 UTC | 2013-03-26 16:13:35 UTC | boolean    |

So I run a where method on an Array... But:

tab.method(:where) #returns:
NameError: undefined method `where' for class `Array'

How can I do a where on a object that doesn't recognize it?? I've a kind of idea:

1.9.3-p385 :164 > arr.klass
 => Spree::Property(id: integer, name: string, presentation: string, created_at: datetime, updated_at: datetime, value_type: string) 

But I really don't understand the mechanism...It's something totally new for me in a object-oriented language.

Thank you for your explanations.

PH

2 Answers 2

0

Good question!

The way the console works is a bit misleading:

p=Product.last #recover the last product created
arr=p.properties #return the properties in an Array
arr.class #return "Array", so it's effectively an Array object.

arr.class returns "Array" because the console and activerecord want to help you as a programmer. So they do a arr.all.class instead of an arr.class.

Do a arr.to_sql and you'll see that this will result in the SQL. An Array object doesn't have the method to_sql.

Because of lazy loading you can use where(:value_type => "boolean") as a method to arr.

Have a look at http://xyzpub.com/en/ruby-on-rails/3.2/queries.html#lazy_loading to read more about lazy loading.

1
  • Thank you a lot! I'll be suspicious about the console outputs in the future. Maybe there's a way to force rails' console to provide authentic result...
    – hachpai
    Mar 27, 2013 at 11:49
0

The thing is that you don't actually get an instance of Array but an instance of ActiveRecord::Relation. This is to let you chain all those directives together and if you try to access the result the underlying relation get's executed and converted to an array. Pry automatically tries to display results so it will trigger those conversions.

You can see that by doing something like this:

[1] pry(main)> Customer.first.contracts ; nil
  Customer Load (0.6ms)  SELECT `customers`.* FROM `customers` LIMIT 1
=> nil

[2] pry(main)> Customer.first.contracts
  Customer Load (0.5ms)  SELECT `customers`.* FROM `customers` LIMIT 1
  Contract Load (0.7ms)  SELECT `contracts`.* FROM `contracts` WHERE `contracts`.`customer_id` = 1
=> [...results...]

[3] pry(main)> class ActiveRecord::Relation
[3] pry(main)*   def to_a
[3] pry(main)*     puts "I converted me (#{(class << self ; self ; end).superclass}) to an Array"
[3] pry(main)*     logging_query_plan do
[3] pry(main)*       exec_queries
[3] pry(main)*     end
[3] pry(main)*   end
[3] pry(main)* end
=> nil

[4] pry(main)> Customer.first.contracts ; nil
I converted me (ActiveRecord::Relation) to an Array
  Customer Load (0.5ms)  SELECT `customers`.* FROM `customers` LIMIT 1
=> nil

[5] pry(main)> Customer.first.contracts
I converted me (ActiveRecord::Relation) to an Array
  Customer Load (0.6ms)  SELECT `customers`.* FROM `customers` LIMIT 1
I converted me (ActiveRecord::Relation) to an Array
  Contract Load (0.6ms)  SELECT `contracts`.* FROM `contracts` WHERE `contracts`.`customer_id` = 1
=> [...results...]

Step [1]: Only the Customer is getting fetched. The contracts-relation remains unexecuted because Pry doesn't try to access it (due to the ; nil)

Step [2]: Same as 1. but Pry tries to access the relation so we fetch those too.

Step [3]: We override the ActiveRecord::Relation.to_a method. I only added the puts the rest is the original method (using super will result in a loop!).

Step [4]: Repeat 1. and 2. Each conversion now triggers an additional message.

Metaprogramming in Ruby is pretty complex and cause a lot of headaches but I hope this make things clear.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.