开发者

Rails calling action from view

开发者 https://www.devze.com 2023-02-11 23:03 出处:网络
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 wh

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 simpl开发者_如何学运维y 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消