【问题标题】:Rendering an Action's Template from Another Controller从另一个控制器渲染一个动作的模板
【发布时间】:2017-12-01 21:22:13
【问题描述】:

我正在开发一个具有以下设计论坛的项目,其中的帖子具有 cmets。我正在阅读 ruby​​ 指南http://guides.rubyonrails.org/layouts_and_rendering.html#overview-how-the-pieces-fit-together,它说要从另一个动作渲染动作模板,我需要使用类似 render "posts/index" 的东西。

我正在尝试打印该论坛中某个论坛的所有帖子。我已经设置了数据库和模型,但不确定如何处理控制器。

如何在 forums/show/i 中调用帖子/索引(其中 i 是论坛的 id)。

如何打印论坛中的帖子以及如何仅打印与该特定论坛相关的帖子?

当我尝试在论坛控制器的索引功能中调用渲染“帖子/索引”时,我收到以下错误消息:

ActionView::MissingTemplate in Forums#show 


Showing /home/ubuntu/workspace/app/views/forums/show.html.erb where line #26 raised:

Missing partial posts/_index with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/home/ubuntu/workspace/app/views"
  * "/usr/local/rvm/gems/ruby-2.3.4/gems/devise-4.3.0/app/views"

<%= render 'posts/index' %>

以上以红色突出显示。

感谢您的宝贵时间。

【问题讨论】:

  • 您有相互关联的模型吗?如果没有,有什么理由不这样做?
  • @JulianG。我得到了使用has_and_belongs_to_many :x 关联的模型,用于帖子模型和相同的论坛模型(其中 x 是相反的表名)

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


【解决方案1】:

因为你有相互关联的模型,我会这样做。在您的论坛显示视图中:

<%= render partial: 'posts/index', locals: {forum: @forum} %>

然后创建局部视图posts/_index.html.erb:

<% forum.posts.each do |post| %>
   <div><%= post.your_attributes %></div>
   <div><%= render partial: 'comments/index', locals: {forum: forum, post: post} %>
<% end %>

最后创建一个局部视图 cmets/_index.html.erb:

<% post.comments.each do |comment| %>
    <div><%= comment.your_attributes %><div>
<% end %>

locals 选项将这些变量传递给您的局部变量以便在那里使用。

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 2011-06-02
    • 2015-10-25
    • 1970-01-01
    • 2015-07-31
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多