Topic: Optimising my controller and view

Hi,

I'm making a site which uses db entry's as navigation, but I'm repeating myself several times (because I dont know how to make it dry)

This is my code (controller)

def album
     @nav = Cms.find(:all)
  end

  def contact
     @nav = Cms.find(:all)
  end
..
..
..


this is my view :
<%= render :partial => "/layouts/nav_site", :collection => @nav %>
<li><%= link_to_unless_current nav_site.title.to_s , :controller => "site", :action => "index", :permalink => nav_site.permalink.to_s %></li>

Can someone help me drying my code

Re: Optimising my controller and view

If you only use the variable in this one render call, it'S perfectly acceptable to do this:

<%= render :partial => "/layouts/nav_site", :collection => Cms.find(:all) %>
#

As the Code here is only for navigation  and not related to the core function of your controller ("do operations for resource XY") it can go into the view without any problems.

alternatively you could use a before_filter:

#controller
class MYController
  before_filter :getnav

# actions

private
  def getnav
    @nav = Cms.find(:all)
  end
end

#view
<%= render :partial => "/layouts/nav_site", :collection => @nav %>


But compared to the first solution, this produces more code and pollutes our controller with stuff that it shold not be responsible for.

Re: Optimising my controller and view

Hi Duplex,

I'm trying this out and I'm getting this error:

syntax error, unexpected kEND, expecting $end

but I did what you told me

  private
    def getnav
      @nav = Cms.find(:all)
    end
  end

Did I do something wrong?

Re: Optimising my controller and view

i guess you are missing an "end" somewhere in your controller code, or have one too much (dont remember exactly which one this error refers to).

I think its rather the first... The last "end" in my code refers to the "end" of the class block. (class blabla ... end). I guess you already had that and now inserted an additional "end" thats not nessessary.

Re: Optimising my controller and view

There was an end to many, thanks for your help