【问题标题】:Rails action inheritance and nested resourcesRails 动作继承和嵌套资源
【发布时间】:2011-08-09 03:33:56
【问题描述】:

我在我的 Rails 应用程序中使用嵌套资源,如下所示:

resources :devices, :except => [:edit] do
    resources :services, :only => [:index, :destroy], :controller => "devices/services"
    resources :alerts,   :only => [:index, :destroy], :controller => "devices/alerts"
end

现在我想做的是让设备/显示视图成为嵌套资源的“布局”,并且 我定义的任何其他子操作。

所以说我的 devices/show.html.erb 看起来像这样:

<div class="resource">
  <div class="sidebar">
    <ul>
      <li><%= active_link_to "General", @device, :active => :exclusive %></li>
      <li><%= active_link_to "Services", device_services_path(@device) %></li>
      <li><%= active_link_to "Alerts", device_alerts_path(@device) %></li>
      etc..
    </ul>
  </div>
  <div class="data">
    <%= render "shared/flash_messages" %>
    <%= yield %>
  </div>
</div>

那么我该如何渲染子视图(devices/services/index.html.erb、devices/alerts/index.html.erb),其中(假设的)yield 在#data div 中?

【问题讨论】:

  • 你有什么问题?
  • yield 仅适用于布局 AFAIK。我试过这个,产量没有呈现任何东西......
  • 那么你的问题是关于如何使用yield?在这种情况下,您应该考虑使用 content_for guides.rubyonrails.org/…
  • 是的。我完全忘记了这一点。我使用它和嵌套布局来解决这个问题。谢谢!!
  • 大声笑 :) 很高兴你把它整理好了

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

您的问题似乎与继承和嵌套资源完全无关。

如果您想知道如何使用 yield 命令,我在评论中针对您的问题发布了一个链接,但这里有一个专门针对您的代码的示例

<div class="resource">
  <div class="sidebar">
    <ul>
      <li><%= active_link_to "General", @device, :active => :exclusive %></li>
      <li><%= active_link_to "Services", device_services_path(@device) %></li>
      <li><%= active_link_to "Alerts", device_alerts_path(@device) %></li>
      etc..
    </ul>
  </div>
  <div class="data">
    <%= render "shared/flash_messages" %>
    <%= yield :nested_resources %>
  </div>
</div>

然后,无论您想在该 div 中放置任何内容,都将其包装在 content_for :nested_resources 块中,例如 在某处的视图模板中

<% content_for :nested_resources do %>
  <!-- whatever code you would normally have in your view template -->
<% end %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多