Basically, I have an app with a tagging system and when someone searches for tag ‘badger’, I want it to return records tagged “badger”, “Badger” and “Badgers”.
With a single tag I can do this to get the records:
@notes = Tag.find_by_name(params[:tag_name]).notes.order("created_at DESC")
and it works fine. However if I get multiple tags (this is just for upper and lower case – I haven’t figured out the ‘s’ bit either yet):
Tag.find(:all, :conditions => [ "lower(name) = ?", 'badger'])
I can’t use .notes.order(“created_at DESC”) because there are multiple results.
So, the question is…. 1) Am I going about this the right way? 2) If so, how do I get all my records back in order?
Any help much appreciated!
One implementation would be to do:
However you should be aware that this is what is known as an N + 1 query, in that it makes one query in the outer section, and then one query per result. This can be optimized by changing the first query to be:
If you are using Rails 3 or above, it can be re-written slightly: