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个
one:
id: 1
category_name: a
two:
id: 2
category_name: b
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]: [4;35;1mCategory Load (0.016000)[0m [0mSELECT * FROM category WHERE (category.`id` = 1) [0m
Nov 06 10:35:20 13cc97e4810e43f rails[3044]: [4;36;1mGrp Columns (0.000000)[0m [0;1mSHOW FIELDS FROM grp[0m
Nov 06 10:35:20 13cc97e4810e43f rails[3044]: [4;35;1mSQL (0.000000)[0m [0mSELECT count(*) AS count_all FROM grp WHERE (grp.category_id = 1) [0m
Nov 06 10:35:20 13cc97e4810e43f rails[3044]: [4;36;1mCategory Load Including Associations (0.000000)[0m [0;1mSELECT 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) [0m
用了include语句后 model中定义的:limit=>5会失效.
实际上你会发现,不仅:limit会失效,如果加入其他参数如 :order, :offset等都会失效