我开发的网站,其中有文章和新闻页面,我想添加两个评论的机会。我使用多态关联。
class Article < ActiveRecord::Base
has_many :commentaries, :as => :commentable
end
class News < ActiveRecord::Base
has_many :commentaries, :as => :commentable
end
class Commentary < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end我想在可注释对象下面显示注释
视图/文章/show.html.erb
<p>
<b>Title:</b>
<%= @article.title %>
</p>
<p>
<b>Short text:</b>
<%= @article.short_text %>
</p>
<p>
<b>Full text:</b>
<%= @article.full_text %>
</p>
<%= render 'commentaries/form' %>views/news/show.html.erb
<p>
<b>Title:</b>
<%= @news.title %>
</p>
<p>
<b>Text:</b>
<%= @news.text %>
</p>
<p>
<b>Created:</b>
<%= @news.created %>
</p>视图/评论/_form.html.erb
<h1>Comments</h1>
<ul id="comments">
<% @commentaries.each do |comment| %>
<li><%= comment.content %></li>
<% end %>
</ul>
<h2>New Comment</h2>
<% form_for [@commentable, Comment.new] do |form| %>
<ol class="formList">
<li>
<%= form.label :content %>
<%= form.text_area :content, :rows => 5 %>
</li>
<li><%= submit_tag "Add comment" %></li>
</ol>
<% end %>和我的控制器:
class CommentariesController < ApplicationController
def index
@commentable = find_commentable
@commentaries = @commentable.commentaries
end
end
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
end
end当我转到mysite/文章/1时,我得到了错误: nil:NilClass的未定义方法‘`each’,因为我的文章中没有@commentable,控制器和注释控制器的代码不会执行。
如何在文章/展示页面上执行评论控制器的索引操作?
发布于 2012-12-24 02:53:03
添加局部变量:commentable => @article,同时呈现注释窗体
<%= render 'commentaries/form', :commentable => @article %>从分部视图views/commentaries/_form.html.erb访问局部变量
<% commentable.commentaries.each do |comment| %>
...
<% end %>
...
<% form_for [commentable, Comment.new] do |form| %>
...
<% end %>https://stackoverflow.com/questions/14013637
复制相似问题