Rails calling action from view

早过忘川 提交于 2019-12-10 10:14:02

问题


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:


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.



来源:https://stackoverflow.com/questions/5031905/rails-calling-action-from-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!