RSpec:Bogus SQL错误?

时间:2011-03-22 20:11:00

标签: sql ruby-on-rails testing rspec

我有一个Photo模型,使用以下方法按名称搜索相关标签:

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)>'

因此,代码可以工作,但测试失败了。我的测试中我做错了什么?

2 个答案:

答案 0 :(得分:5)

似乎它在抱怨,因为你按ID分组,照片和标签表都有id(数据库不知道你是不是指photos.id或taggings.id,因此'模糊'错误)。尝试在tagged_with方法中将.group(:id)更改为.group('photos.id')

答案 1 :(得分:5)

要修复此错误,请明确要分组的内容,以便执行以下操作:

joins(:tags).where('tags.name' => array ).group("photos.id")

即使您的代码现在正常运行,使用此查询您确实希望显式。这是因为您正在处理的所有表格(标记和照片)都有ID列。