Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Sidebar with Rails layout

For instance, i want to have my sidebar to have several dynamic content. Using other method will lead me to put query codes into View, which is not a good idea at all. I would like to keep any query in my Controller.

Currently as i know there are several ff. method:

Render a shared partial -> No where to put the query

render :partial => "shared/sidebar"

Content For -> Additional details in the comment

<%= yield :sidebar %>
<% content_for :sidebar do %>
  <a href="http://www.netscape.com">Netscape</a><br>
  <a href="http://www.lycos.com">Lycos</a><br>
  <a href="http://www.walmart.com">Wal Mart</a><br>
<% end %>

3rd is write it directly to the layout file.

So how should I make this work?

like image 921
DucDigital Avatar asked Aug 18 '10 10:08

DucDigital


2 Answers

IF you want this in every view, you can place the method that populates the necessary data in application_controller and use a before_filter to trigger it.

before_filter :load_sidebar

def load_sidebar
  @data = Thingy.find(:all)
end

Then your partial or content_for element checks for @data and processes.

like image 105
Toby Hede Avatar answered Oct 06 '22 03:10

Toby Hede


If you wanted to reduce the amount of code in your application_controller.rb, you may want to consider using the Cells gem.

This would allow you to define your 'query' in a separate cell controller, and you would render the content for it using something like render_cell :sidebar, :myquery inside your view.

like image 43
davetapley Avatar answered Oct 06 '22 01:10

davetapley