user1925404
user1925404

Reputation: 33

Ruby on Rails. Views in polymorphic associations

I develop site which has articles and news pages and I would like to add opportunity to comment both. I use polymorphic associations.

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

I would like to show comments below commentable object

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>

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 %>

And my controllers:

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

When I go to mysite/article/1 I get error undefined method `each' for nil:NilClass, because there isn't @commentable in my article controller and commentaries controller's code doesn't execute.

How to execute index action of commentaries controller on article/show page?

Upvotes: 3

Views: 1748

Answers (1)

siddick
siddick

Reputation: 1478

Add local variable:commentable => @article, while rendering the commentaries form

<%= render 'commentaries/form', :commentable => @article %>

Access the local variable from you partial view views/commentaries/_form.html.erb

<% commentable.commentaries.each do |comment| %>
  ...
<% end %>
...
<% form_for [commentable, Comment.new] do |form| %>
  ...
<% end %>

Upvotes: 3

Related Questions