0

I have the following method in my Product model:

def has_feature? (feature_name)
  self.features.where(:name=>feature_name).present?
end

This seems to be very slow. Is there a better way of checking to see if my product has a feature with a given name?

Abram
  • 39,950
  • 26
  • 134
  • 184

2 Answers2

1

One other way of writing this is using scope in your Feature model and see if it helps and do a present? on the resulting output of that scope

scope :includes_feature, lambda{ |feature|
  { :name => feature }
}

so finally what you can do is product.features.includes_feature(feature_name)

Raghu
  • 2,543
  • 1
  • 19
  • 24
1

.present? isn't a standard method on an ActiveRecord::Relation which is what where returns. Calling .present? is fetching all of the features with the given name, changing into an array and then calling .present? on the array.

If you call .exists? instead then the database query that is performed is slightly more optimised to checking whether that feature exists or not.

However, I'm not sure you'll notice much of a performance differences between the two options. The most likely cause is that you're missing a database index. Assuming that your association is Product has_many :features the database query that will get generated would be improved by an index on both features.product_id and features.name.

Shadwell
  • 34,314
  • 14
  • 94
  • 99
  • Would you suggest adding the indexes and calling .exists? or adding indexes and using scoping as suggested by Raghu – Abram Sep 20 '13 at 21:42
  • I would suggest adding an index with both fields and then from there using the approach that you feel most comfortable with. – Shadwell Sep 20 '13 at 21:47
  • Ok, I would be comfortable with either, I just meant .. what is best from a speed perspective... I'll assume from your response that it doesn't matter. – Abram Sep 20 '13 at 21:53
  • Sorry, I was implying, too subtly, that there won't be any appreciable difference between the two approaches after the index is added. – Shadwell Sep 20 '13 at 22:04
  • Not a problem. I have one more related question if you feel so inclined http://stackoverflow.com/questions/18926627/adding-index-has-many-through-relationship – Abram Sep 20 '13 at 22:07