【问题标题】:Ruby on Rails. Views in polymorphic associationsRuby on Rails。多态关联中的视图
【发布时间】:2012-12-23 18:42:03
【问题描述】:

我开发了包含文章和新闻页面的网站,我想增加对两者发表评论的机会。我使用多态关联。

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

我想在可注释对象下方显示 cmets

views/articles/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/article/1 时,我收到错误 undefined method `each' for nil:NilClass,因为我的文章控制器中没有 @commentable 并且评论控制器的代码没有执行。

如何在文章/节目页面上执行评论控制器的索引操作?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    添加局部变量:commentable =&gt; @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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多