RSpec:Bogus SQL错误?

And*_*rew 3 sql testing rspec ruby-on-rails

我有一个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
Run Code Online (Sandbox Code Playgroud)

如果我在控制台中使用它,它会产生我期望的结果:

Photo.tagged_with('foo, bar, baz')
# Returns unique photos with tags named foo, bar, or baz
Run Code Online (Sandbox Code Playgroud)

但是,我尝试使用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
Run Code Online (Sandbox Code Playgroud)

此测试失败,并出现以下错误:

  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)>'
Run Code Online (Sandbox Code Playgroud)

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

Bre*_*der 5

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


Mik*_*wis 5

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

joins(:tags).where('tags.name' => array ).group("photos.id")
Run Code Online (Sandbox Code Playgroud)

即使您的代码现在正常工作,使用此查询您确实希望明确.这是因为您正在处理的所有表(标记和照片)都有一个ID列.