RSpec: Bogus SQL error?

I have a photo model with the following method for finding related tags by name:

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

If I use this in the console, it gives what I expect:

Photo.tagged_with('foo, bar, baz')
# Returns unique photos with tags named foo, bar, or baz

However, I tried to build this using a test in RSpec, and the test failed. Here is my test:

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

This test fails with the following error:

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

So, the code works, but the test fails. What am I doing wrong in my test?

+3
source share
2 answers

He seems to be complaining because you are grouping by id, and the tables with photos and tags have identifiers (the database does not know if you have photos.id or taggings.id, therefore, an "ambiguous" error). Try changing .group(:id)to .group('photos.id')in the tagged_with method.

+5

, , , :

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

, . , , ( ), .

+5

All Articles