Topic: Help with SQL refactoring

Hi all, is it possible to do the following in a more agile way. Basically what I wanna do is use all my unique taggable_types in my taggins database as a key referencing all the results for that specific taggable_type in a Hash. The hash will look something like this structure wise

@tags = {
  'Product' => [{"tag1", "id"=>"1"}, {"tag2", "id"=>"2"}],
  'Article' => [{"tag1", "id"=>"1"}, {"tag2", "id"=>"2"}]
}

Here is the code i would like to refactor if at all possible.

groups = Tagging.find(:all, :group=>"taggable_type")
@tags = {}
for group in groups
  @tags[group.taggable_type] = Tagging.find(:all, :select=>'tags.*', :joins=>"JOIN tags ON tags.id = taggings.tag_id", :conditions=>"taggable_type='#{group.taggable_type}'", :group=>"tag_id", :order=>"tags.name ASC")
end

Everything works perfectly i'm just think that there must be a better way.

Thanx guys

Last edited by sonic921 (2007-10-08 09:10:11)

Re: Help with SQL refactoring

You can use the group_by method like this:

@tags = Tag.find(:all)
@tag_groups = @tags.group_by { |t| t.tagging.taggable_type }

Not sure if that's exactly what you want, but it looks like it will be a better solution.

Railscasts - Free Ruby on Rails Screencasts

Re: Help with SQL refactoring

Thank you very much ryan... That solution didn't work for my current scenario  but i've found a use for that exact snippet already... Thank you very much