Created
January 13, 2013 16:36
-
-
Save ByScripts/4524954 to your computer and use it in GitHub Desktop.
Problem that I don't understand with Rails relations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# $ rails new foo | |
# $ cd foo | |
# $ rails generate model Category position:integer parent_id:integer name:string children_count:integer | |
# $ rake db:migrate | |
# Modified app/models/category.rb | |
class Category < ActiveRecord::Base | |
attr_accessible :position, :parent_id, :name | |
has_many :children, class_name: "Category", foreign_key: :parent_id, inverse_of: :parent | |
belongs_to :parent, class_name: "Category", counter_cache: :children_count, inverse_of: :children | |
default_scope order('position ASC') | |
def last_child | |
children.last | |
end | |
end | |
# Rails console | |
c1 = Category.create(name: "Category 1") | |
Category.create(name: "Category 1.1", parent_id: c1.id) | |
Category.create(name: "Category 1.2", parent_id: c1.id) | |
c2 = Category.create(name: "Category 2") | |
Category.create(name: "Category 2.1", c2.id) | |
c = Category.first | |
c.last_child # Makes a DB request | |
c.last_child # Makes a DB request | |
c.last_child # Makes a DB request | |
c.children # Makes a DB request | |
c.children # No longer makes a DB request | |
c.last_child # No longer makes a DB request | |
c.last_child # No longer makes a DB request | |
c.last_child # No longer makes a DB request | |
# Tried changing this in the model, but the problem is the same | |
# When calling last child without calling children alone before | |
# there is no use of the cached query | |
def last_child | |
children && children.last | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment