Rails invokes an action from a view

I hope I have a simple question, but I can't make my life seem to find the answer. Just started working with RoR, but used to be from ASP MVC. I have a problem with partial representations whose local variables are not necessarily related to the variables of the main form. For example, on a blog, I'm trying to display a sidebar that will link to an archive.

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

A partial view of _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 facing is that if I just do a sidebar rendering in my main view, the action does not seem to be called, and @post_months is always zero. Is it possible to call an action directly from the view and just make it a "sidebar"? In ASP MVC, I used only the ChildActionOnly and Render.Action sidebars from mainview, but in RoR I don't know at all. Any help is appreciated!

+3
source share
1 answer

, , yout , . , , ApplicationHelper , , .

. , , , .

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

, , , , , , .

.

+1

Source: https://habr.com/ru/post/1792848/


All Articles