我有一个具有以下方法的照片模型,可以按名称搜索关联的标签:
class Photo < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
...
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
joins(:tags).where('tags.name' => array ).group(:id)
end
...
end
如果我在控制台中使用它,它的输出将完全符合我的期望:
Photo.tagged_with('foo, bar, baz')
# Returns unique photos with tags named foo, bar, or baz
但是,我尝试使用RSpec中的测试来构建它,但是测试失败。这是我的测试:
describe "tags" do
it "should return a list of photos matching a string of tags" do
t1 = Tag.create(:name=>'test')
t2 = Tag.create(:name=>'bar')
t1.photos << Photo.find(1,2,3)
t2.photos << Photo.find(3,4)
t1.save
t2.save
Photo.tagged_with('test').should have(3).photos
Photo.tagged_with('bar').should have(2).photos
Photo.tagged_with('test, bar').should have(4).photos
end
end
该测试失败,并出现以下错误:
1) Photo tags should return a list of photos matching a string of tags
Failure/Error: Photo.tagged_with('test').should have(3).photos
ActiveRecord::StatementInvalid:
SQLite3::SQLException: ambiguous column name: id: SELECT COUNT(*) AS count_all, id AS id FROM "photos" INNER JOIN "taggings" ON "photos"."id" = "taggings"."photo_id" INNER JOIN "tags" ON "tags"."id" = "taggings"."tag_id" WHERE "tags"."name" IN ('test') GROUP BY id
# ./spec/models/photo_spec.rb:84:in `block (3 levels) in <top (required)>'
因此,代码有效,但测试失败。我的考试做错了什么?
最佳答案
似乎是在抱怨,因为您按ID分组,并且photo和taggings表都具有id(数据库不知道您是指photos.id还是taggings.id,因此出现“模棱两可”的错误)。尝试在您的agged_with方法中将.group(:id)
更改为.group('photos.id')
。