diff --git a/app/models/item.rb b/app/models/item.rb index 57653ea0..7f402f50 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -65,18 +65,22 @@ class Item < ActiveRecord::Base def narrow(scope) items = Table(:objects) - if @property == 'species' + if @property == 'species' || @property == 'only' species = Species.find_by_name(self) raise ArgumentError, "Species \"#{self.humanize}\" does not exist" unless species # TODO: add a many-to-many table to handle this relationship, if # performance becomes an issue ids = items[:species_support_ids] - condition = ids.eq('').or(ids.matches_any( - species.id, - "#{species.id},%", - "%,#{species.id},%", - "%,#{species.id}" - )) + if @property == 'species' + condition = ids.eq('').or(ids.matches_any( + species.id, + "#{species.id},%", + "%,#{species.id},%", + "%,#{species.id}" + )) + else + condition = items[:species_support_ids].eq(species.id.to_s) + end elsif @property == 'description' || @property.blank? column = @property == 'description' ? :description : :name condition = items[column].matches("%#{self}%") diff --git a/spec/models/item_spec.rb b/spec/models/item_spec.rb index db2e8fca..54a9648d 100644 --- a/spec/models/item_spec.rb +++ b/spec/models/item_spec.rb @@ -143,6 +143,16 @@ describe Item do Item.search('-species:aisha').count.should == 1 end + specify "should search by only:species" do + Factory.create :item, :species_support_ids => [1], :name => 'a' + Factory.create :item, :species_support_ids => [1,2], :name => 'b' + Factory.create :item, :species_support_ids => [], :name => 'c' + Item.search('only:acara').map(&:name).should == ['a'] + Item.search('only:aisha').count.should == 0 + Item.search('-only:acara').map(&:name).should == ['b', 'c'] + Item.search('-only:aisha').map(&:name).should == ['a', 'b', 'c'] + end + specify "should be able to negate word in search" do query_should 'hat -blue', :return => [