Skip to content
This repository was archived by the owner on Aug 13, 2020. It is now read-only.

Files

Latest commit

 

History

History
74 lines (56 loc) · 1.56 KB

comments.md

File metadata and controls

74 lines (56 loc) · 1.56 KB

Comments

Adding comments to a resource

  1. Add the following to the Foo model:
acts_as_commentable
  1. Create controller:
bin/rails g controller FooComments index --no-helper --skip-routes
  1. Add route
scope "/foos/:foo_id" do
  resources :foo_comments, only: [:index], path: "/comments"
end
  1. Setup controller
class FooCommentsController < ApplicationController
  before_action :authenticate_user!
  before_action :authorize_view!, only: :index
  before_action :set_foo, only: :index

  def index
    @comments = @foo.comment_threads.order(created_at: :desc)
  end

  private

  def set_foo
    @foo = if authorized_user.can_admin_system?
      Foo.find(params[:foo_id])
    else
      current_user.foos.find(params[:foo_id])
    end
  end

  def authorize_view!
    render_forbidden unless authorized_user.can_view_comments?
  end
end
  1. Update the view
<%= render(PageComponent.new(subject: @foo, sidebar: true, tabs: true)) do |component| %>
  <% component.with(:header) do %>
    <%# Common header layout %>
  <% end %>
  <% component.with(:body) do %>
    <%= render(CommentsComponent.new(commentable: @foo, comments: @comments)) %>
  <% end %>
<% end %>
  1. Update the Foo tabs and sidebar if needed
<%= tag.li (nav_item_link name: "Comments", path: foo_comments_path(subject)) if authorized_user.can_view_comments? %>
<%= active_link_to "Comments", foo_comments_path(foo), class: "menu-link", tabindex: -1, wrap_tag: :li, wrap_class: "menu-item" if authorized_user.can_view_comments? %>