55502f40dc8b7c769880b10874abc9d0

I have a method (LinkCategory::all_with_logo) that gets all the link_categories and its related links. I would like to get only the link_categories that contains some links (i.e. has_many links) which have a logo image (logo_file_name not nil) assigned to them.

I'm sure there is a better way to write this, but Rails is still new for me...

Thanks in advance!

# link_categories has_many links
create_table "link_categories", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "links", :force => true do |t|
  t.string   "label"
  t.string   "address"
  t.text     "description"
  t.integer  "link_category_id"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "logo_file_name"
  t.string   "logo_content_type"
  t.integer  "logo_file_size"
  t.datetime "logo_updated_at"
end

# the method i would like to optimize:

def self.all_with_logo
  categories = all
  ret_categories = []
  categories.each do |linkcategory|
    links = []
    linkcategory.links.each do |link|
      if link.logo_file_name
        links << link
      end
    end
    if links.length > 0
      ret_categories << linkcategory
    end
  end
  ret_categories
end

Refactorings

No refactoring yet !

55502f40dc8b7c769880b10874abc9d0

https://www.google.com/accounts/o8/id?id=AItOawl_CInyr4p6Fw9fCXT3DYEGIiMyGOQDomw

August 2, 2010, August 02, 2010 19:15, permalink

No rating. Login to rate!

I just found something.

def self.all_with_logo
  categories = all(:include=>[:links], :conditions=>"links.logo_file_name IS NOT NULL")
end

Your refactoring





Format Copy from initial code

or Cancel