Search code examples
ruby-on-railspolymorphic-associations

Rails polymorphic link_to parent's show page from children's index page


I have three models

class Comment < ActiveRecord::Base  
  belongs_to :commentable, :polymorphic => true
end

class Movie < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class TV < ActiveRecord::Base
  has_many :comment, :as => :commentable
end

While in my home page, people are able to see top comments like a comment's index page.

I currently doing like below, but it is not work

<div>
  <% @comments.each do |comment| %>
    <%= simple_format comment.content %>
    <%= link_to comment.commentable_id %>
  <% end %>
</div>

It seems I missed something. What should I add to make it possible to link to parent's show page through the comment?

That is, for example, someone comment "This movie is awesome" on a movie, Transformer.

People are also able to see the comment on comment's index page. Then there is a link bring them to Transformer's show page so that user are able to see more details.

Do I need to do anything on controller as well?


Solution

  • figure it out just edit like below

    <div>
      <% @comments.each do |comment| %>
        <%= simple_format comment.content %>
        <%= link_to **"LINK", comment.commentable** %>
      <% end %>
    </div>