2
我開發的網站有文章和新聞頁面,我想增加評論兩者的機會。我使用多態關聯。Ruby on Rails。多態協會的意見
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
我想顯示下面commentable對象
的意見/用品/ 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' %>
的意見/新聞/ show.html.erb
<p>
<b>Title:</b>
<%= @news.title %>
</p>
<p>
<b>Text:</b>
<%= @news.text %>
</p>
<p>
<b>Created:</b>
<%= @news.created %>
</p>
views/commentaries/_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,收到錯誤未定義的方法`每個」近親:NilClass,因爲沒有@commentable在我的文章控制器評論控制器的代碼不會執行。
如何在文章/展示頁面上執行評論控制器的索引動作?