我在 rails 3 app 上发现了一个不寻常的情况。
考虑以下模型:
class Genre < ActiveRecord::Base
has_many :banner_genres, :dependent => :destroy
has_many :banners, :through => :banner_genres
...
class BannerGenre < ActiveRecord::Base
attr_accessible :banner_id, :banner, :genre_id, :genre, :position
belongs_to :genre
belongs_to :banner
...
class Banner < ActiveRecord::Base
has_many :banner_genres, :dependent => :destroy
has_many :genres, :through => :banner_genres
...
现在,如果我有一个带有横幅的流派,我会在 rails 控制台中看到以下几行:
1.9.3p362 :005 > g = Genre.find 62
Genre Load (0.8ms) SELECT "genres".* FROM "genres" WHERE "genres"."id" = $1 LIMIT 1 [["id", 62]]
=> #<Genre id: 62, ...
1.9.3p362 :006 > g.banner_genres.any?
(0.5ms) SELECT COUNT(*) FROM "banner_genres" WHERE "banner_genres"."genre_id" = 62
=> true
1.9.3p362 :007 > g.banners
Banner Load (1.0ms) SELECT "banners".* FROM "banners" INNER JOIN "banner_genres" ON "banners"."id" = "banner_genres"."banner_id" WHERE "banner_genres"."genre_id" = 62 ORDER BY position
=> [#<Banner id: 446, ...
1.9.3p362 :008 > g.banners.any?
=> false
为什么要.any?
退货false
?我通过在同一个项目上的关联与另一个 has_many 联系,它返回true
。
编辑:
在这里传递代码时我有一个错字。它是 has_many 上的 banner_genres。不是流派横幅。
反向关联也按预期工作:
1.9.3p362 :004 > b = Banner.find 446
Banner Load (1.1ms) SELECT "banners".* FROM "banners" WHERE "banners"."id" = $1 ORDER BY position LIMIT 1 [["id", 446]]
=> #<Banner id: 446...
1.9.3p362 :005 > b.genres.any?
(0.8ms) SELECT COUNT(*) FROM "genres" INNER JOIN "banner_genres" ON "genres"."id" = "banner_genres"."genre_id" WHERE "banner_genres"."banner_id" = 446
=> true
编辑 2
更奇怪的控制台输出:
1.9.3p362 :007 > g.banners.class
=> Array
1.9.3p362 :008 > g.banners.any?
=> false
1.9.3p362 :004 > g.banners.any? {|b| b}
=> true
1.9.3p362 :006 > g.banners.count
(0.9ms) SELECT COUNT(*) FROM "banners" INNER JOIN "banner_genres" ON "banners"."id" = "banner_genres"."banner_id" WHERE "banner_genres"."genre_id" = 62
=> 1
1.9.3p362 :009 > g.banners.to_a.any?
=> true
编辑 3
g.banner_genres
BannerGenre Load (0.7ms) SELECT "banner_genres".* FROM "banner_genres" WHERE "banner_genres"."genre_id" = 62
=> [#<BannerGenre id: 4, genre_id: 62, banner_id: 446, position: 1, created_at: "2013-03-15 16:41:10", updated_at: "2013-03-15 16:41:10">]
编辑 4由 Aleks 提出
您能否显示在 g.banners.any 上显示的查询?和 g.banners。 这是完全相同的查询,甚至更奇怪。我也没有覆盖任何?任何地方的方法。
1.9.3p362 :037 > g.banners(true)
Banner Load (1.0ms) SELECT "banners".* FROM "banners" INNER JOIN "banner_genres" ON "banners"."id" = "banner_genres"."banner_id" WHERE "banner_genres"."genre_id" = 62 ORDER BY position
=> [#<Banner id: 446, ...
1.9.3p362 :038 > g.banners(true).any?
Banner Load (1.2ms) SELECT "banners".* FROM "banners" INNER JOIN "banner_genres" ON "banners"."id" = "banner_genres"."banner_id" WHERE "banner_genres"."genre_id" = 62 ORDER BY position
=> false
1.9.3p362 :039 > g.banners.method(:any?)
=> #<Method: Array(Enumerable)#any?>