jeudi 25 février 2016

Why does calling `respond_to?("find_by_identifier")` on a relation instantiate all of the items

class Collection < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  after_initialize :do_stuff

  def do_stuff
    STDERR.puts "Got here"
  end
end

collection = Collection.where(identifier: "foo").first ; nil
  Collection Load (0.6ms)  SELECT `collections`.* FROM `collections` WHERE `collections`.`identifier` = 'foo' LIMIT 1

[22] pry(main)> collection.items.find_by_identifier!("280") ; nil
  Item Load (1.0ms)  SELECT `items`.* FROM `items` WHERE `items`.`collection_id` = 42 AND `items`.`identifier` = 'bar' LIMIT 1
Got here

[23] pry(main)> collection.items.respond_to?("find_by_identifier!") ; nil
  Item Load (9.7ms)  SELECT `items`.* FROM `items` WHERE `items`.`collection_id` = 42
[Hundreds of of "Got here"s]

In ActiveRecord version 3.2.x, why does running find_by_identifier! only cause one item to be instantiated, but calling respond_to?("find_by_identifier!") cause all of the items in the has_many relationship to be instantiated?

Aucun commentaire:

Enregistrer un commentaire