3

Hopefully have a simple question here but I cannot for the life of me seem to find the answer. Just started working with RoR but came from ASP MVC before. I am having an issue rendering partial views whose local variables are not necessarily tied to the variables of the main view. For instance, with a blog I am trying to render a sidebar that will link to the archive.

def sidebar
  @blog_posts = Blog.all(:select => "created_at")
  @post_months = @blog_posts.group_by { |m| m.created_at.beginning_of_month }
end

The partial view _sidebar is as follows:

<div class="archives">
  <h4>Blog Archive</h4>
    <% @post_months.sort.reverse.each do |month, posts| %>
    <%= link_to "#{h month.strftime("%B %Y")}: #{posts.count}", archive_path(:timeframe => month) %>
<% end %>
</div>

The problem I am having is that if I simply do a render 'sidebar' within my main view the action does not seem to be called and @post_months is always nil. Is it possible to call the action directly from the view and simply have that render 'sidebar'? In ASP MVC I used to just make the sidebar a ChildActionOnly and Render.Action from the mainview, but in RoR I am completely clueless. Any help is appreciated!

1
  • good question, I've been wondering about this myself, coming from a symfony background where beside partials, there are components (which are partial views with controller code to support them)
    – matei
    Feb 17, 2011 at 16:54

1 Answer 1

1

I think what's happening here is that yout sidebar is being treated as a partial and your controller method is never being called. In that case I'd put the code currently contained in the sidebar controller method into either the ApplicationHelper module or the helper module of the current view, depending on whether or not you'd need to render the sidebar from other views.

You'd need to adapt the code a bit to work in a module. Rather than setting a session variable you should have the methods return the values you want.

Module SomeModule
  def blog_posts
    Blog.all :select => "created_at"
  end

  def post_months
    blog_posts.group_by { |m| m.created_at.beginning_of_month }
  end
end

Of course, that may very well need to be refactored and might not work as written, but that's the general idea I'd go with.

Good Luck.

2
  • thanks for the response that did the trick. easier to do in ASP MVC but i suppose this is a "cleaner" MVC solution.
    – Will Ayd
    Feb 17, 2011 at 17:14
  • here is an article that sums this up
    – matei
    Feb 17, 2011 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.