Rails经常犯的错误二 - :include自定义的子集合

本文首发于: 三人行RubyOnRails话吧 , 转帖请注明出处.

一.创建两个表:

CREATE TABLE category (
  id INT NOT NULL AUTO_INCREMENT,
  category_name VARCHAR(255) NOT NULL,
  PRIMARY KEY(id)
)

CREATE TABLE grp (
  id INT NOT NULL AUTO_INCREMENT,
  category_id INT NOT NULL,
  grp_name VARCHAR(255) NOT NULL,
  PRIMARY KEY(id),
  INDEX idx_grp_category_id(category_id)
)

二.定义关系:

class Category < ActiveRecord::Base
  has_many :grp
  has_many :i_grp, :class_name => 'Grp', :limit=>5
end

class Grp < ActiveRecord::Base

  belongs_to :category

end

定义i_grp的是为了满足需求取每个category下的grp,最多5个

 

三.做测试,定义fixtures(category为1的grp共有6个):

  • category.yml

one:
  id: 1
  category_name: a
two:
  id: 2
  category_name: b

  • grp.yml

one:
  id: 1
  category_id: 1
  grp_name: a
two:
  id: 2
  category_id: 1 
  grp_name: b
three:
  id: 3
  category_id: 1 
  grp_name: c
four:
  id: 4
  category_id: 1 
  grp_name: d   
five:
  id: 5
  category_id: 1 
  grp_name: e  
six:
  id: 6
  category_id: 1 
  grp_name: f

 

 

四.写测试类

category_test.rb

class CategoryTest < Test::Unit::TestCase
  fixtures :category,:grp
 
  def test1
    category = Category.find(1)   
    p 'no include category.i_grp.size = ' + category.i_grp.size.to_s
    category2 = Category.find(1,:include=>'i_grp')
    p 'has include category.i_grp.size = ' + category2.i_grp.size.to_s   
  end
end

打印出来的结果如下:

"no include category.i_grp.size = 5"                       --》期望的结果
"has include category.i_grp.size = 6"                     --》非预期的结果

为什么会出现这种情况,去看看日志test.log

Nov 06 10:35:20 13cc97e4810e43f rails[3044]: Category Load (0.016000)   SELECT * FROM category WHERE (category.`id` = 1) 
Nov 06 10:35:20 13cc97e4810e43f rails[3044]: Grp Columns (0.000000)   SHOW FIELDS FROM grp
Nov 06 10:35:20 13cc97e4810e43f rails[3044]: SQL (0.000000)   SELECT count(*) AS count_all FROM grp WHERE (grp.category_id = 1) 
Nov 06 10:35:20 13cc97e4810e43f rails[3044]: Category Load Including Associations (0.000000)   SELECT category.`id` AS t0_r0, category.`category_name` AS t0_r1, grp.`id` AS t1_r0, grp.`category_id` AS t1_r1, grp.`grp_name` AS t1_r2 FROM category LEFT OUTER JOIN grp ON grp.category_id = category.id WHERE (category.`id` = 1) 

用了include语句后 model中定义的:limit=>5会失效.

实际上你会发现,不仅:limit会失效,如果加入其他参数如 :order, :offset等都会失效



你可能感兴趣的:(F#,Rails,ActiveRecord)