ruby - Rails 从 View 中调用操作

标签 ruby ruby-on-rails-3 action partial-views render

希望这里有一个简单的问题,但我似乎无法为我的生活找到答案。刚开始使用 RoR,但之前来自 ASP MVC。我在呈现部分 View 时遇到问题,其局部变量不一定与主视图的变量相关联。例如,对于一个博客,我试图呈现一个将链接到存档的侧边栏。

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

局部 View _sidebar如下:

<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>

我遇到的问题是,如果我只是在我的主视图中执行渲染“侧边栏”,则似乎不会调用该操作,并且@post_months 始终为零。是否可以直接从 View 调用操作并简单地渲染“侧边栏”?在 ASP MVC 中,我曾经只是将侧边栏设为 ChildActionOnly 和主视图中的 Render.Action,但在 RoR 中我完全无能为力。感谢您的帮助!

最佳答案

我认为这里发生的事情是你的侧边栏被视为一个部分,你的 Controller 方法永远不会被调用。在这种情况下,我会将侧边栏 Controller 方法中当前包含的代码放入当前 View 的 ApplicationHelper 模块或辅助模块中,具体取决于您是否需要从其他 View 呈现侧边栏。

您需要稍微调整代码才能在模块中工作。您应该让方法返回您想要的值,而不是设置 session 变量。

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

当然,这很可能需要重构并且可能无法像写的那样工作,但这是我的总体想法。

祝你好运。

关于ruby - Rails 从 View 中调用操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5031905/

相关文章:

ruby-on-rails - `method_missing':#<Rails::Engine::Configuration:0x9d6a6d8> 的未定义方法 `assets' (NoMethodError)

github - Github Action ,摇晃。 git log的pretty = format标志不起作用

python - chromedriver 版本 >74 时出现 MoveTargetOutOfBoundsException 问题

c# - 准备操作以供在另一个线程中使用

ruby - 要求不在规范内工作

ruby-on-rails - Rails as_json 问题 - 如何有效地包含嵌套对象?

ruby - 是否可以将 Ruby 代码嵌入到批处理文件中?

ruby-on-rails - 在 Rails View 中检查 nil 字符串

ruby-on-rails - 使用 Octokit 从组织中检索私有(private)存储库

sql - rails order through count 在其他表上