My comments model is pretty simple and works polymorphically, but I am now adding the ability to hide a comment by the author of a given record across those polymorphic associations.
class Comment < ActiveRecord::Base
attr_accessible :content, :show
belongs_to :commentable, :polymorphic => true
belongs_to :user
end
So, requests, questions, posts, submissions etc… all have comments and are accessing the comments template without issue, but I want to allow the author of the content in those models to show or hide comments (as opposed to flagging, for example) when the application identifies them as the author of the content that is being commented on.
class Request < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
So, I have everything working when there is only one model, by calling the author: @request.user,
but I’m wondering how to call an author using metaprogramming, so the comment view (with help) can determine what model is currently using the comment view.
I’ve done some research into metaprogramming, but have not found the answer.
Here is the code that calls the author (@request.user):
<% if @comments %>
<h1 class="mtop20">Comments</h1>
<% for comment in @comments %>
<% if signed_in? %>
<% if comment.show == true %>
<div class="well comment mtop10">
<% if current_user == @request.user or current_user.has_role? :admin %>
<%= simple_form_for [@commentable, comment] do |f| %>
<div class ="">
<%= f.input :show, :as => :hidden, :input_html => { :value => false } %>
<%= f.submit "Hide Comment", :class => 'btn btn-mini pull-right' %>
</div>
<% end %>
<% end %>
<span>
<%= image_tag comment.user.image.source(:header) %>
<%= link_to comment.user.name, comment.user %></span>
Posted <%= time_ago_in_words(comment.created_at) %> ago
</span>
<p class="mleft20 mtop10"><%= comment.content %></p>
<% if signed_in? %>
<% if current_user.id == comment.user_id or current_user.has_role? :admin %>
<%= link_to 'Edit', polymorphic_path([ comment.commentable, comment], :action => :edit),
:class => 'btn btn-mini mtop5 mleft10' %>
<%= link_to 'Delete', [comment.commentable, comment],
:confirm => 'Are you sure?',
method: :delete,
:class => 'btn btn-mini mtop5' %>
<% end %>
<% end %>
</div>
<% end %>
<% if comment.show == false %>
<p>A comment by <%= comment.user.name %> has been hidden by <%= @request.user.name %></p>
<% if current_user == @request.user or current_user.has_role? :admin %>
<%= simple_form_for [@commentable, comment] do |f| %>
<div class ="">
<%= f.input :show, :as => :hidden, :input_html => { :value => true } %>
<%= f.submit "Show Comment", :class => 'btn btn-mini btn-success' %>
</div>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
<%= render "comments/form" %>
use
comment.commentable.userto access the author of your post.