Topic: Components vs. partials..

Hey guys,

I have an older rails app that uses render_component in a few places to render navigation divs. I understand why components are (very) slow compared to for example a partial now and I want to remove them but I'm not sure how to go about it efficiently.

The way it works now is render_component calls an action in my controller which does a .find :all on my Category model and lists them in the relevant (partial) view inside the application layout.

Since render :partial doesn't run any code I have to move the .find into the actual action being shown or the application controller. But the navigation box isn't shown on every single page (just the pages that show the default application layout.)

So either I move the .find into the application controller and have it send a query to the database which sometimes isn't necessary or I move the .find into the relevant actions, possibly having to duplicate it here and there.

I hope that wasn't too confusing wink Any thoughts would be much appreciated!

-- marsvin

Re: Components vs. partials..

You can use before_filter

before_filter :find_menu, :except => [:index, :edit]

or
before_filter :find_menu, :only => [:edit]

and than..
def find_menu
  navigation = Nav.find(id) # or something like that smile
end

so you don't have to put it in every action

Re: Components vs. partials..

Yeah I was thinking of that.. It still means manually keeping track of which actions need it but it's probably the best way. Thanks smile

Re: Components vs. partials..

If you ever need to stick a bit of code along with a partial, I prefer to use a helper method:

# in template
<%= list_categories %>

# in helper
def list_categories
  categories = Category.find(:all, ...)
  # other logic ....

  render :partial => 'shared/categories', :object => categories
end


However, if all you're doing is a find on the Category model. You might want to move this into the model itself and just call that from the partial.

# in model
def self.custom_find # get a better name
  find(:all, ...)
end

# partial
<% for category in Category.custom_find %>
  ...
<% end %>

Railscasts - Free Ruby on Rails Screencasts

Re: Components vs. partials..

For the record I ended up using Ryan's method, hadn't thought to query the model straight from the view. No duplication or manually assigning methods and it looks nice & clean to boot wink