Search code examples
ruby-on-railsloopsuniqdo-loops

Getting unique values from loop in rails


I've got it so that I have a list of the unique patients a clinician is having a conversation with. I can call up details about the patients but I can't call up anything to do with the associated comment.

app\views\comments\index.html.erb

    <% @comments.map(&:patient).uniq.each_with_index do |comment, index| %>
      <div class="profile-post color-one">
          <span class="profile-post-numb"><%= index+1 %></span>
          <div class="profile-post-in">
              <h3 class="heading-xs"><a><%= link_to "#{comment.first_name} #{comment.last_name}", comment_path(comment) %></a></h3>
              <p><%= comment.diagnosis %><i class="pull-right"><%= link_to "Edit", edit_comment_path(comment) %> <%= link_to "Delete", comment_path(comment), method: :delete, data: {confirm: 'Are you sure you want to delete'} %></i></p>
          </div>
      </div>
    <% end %>

The link_to are also broken since they are supposed to direct to a comment page but are passing patient.id instead of comment.id.

comments_conrtoller.rb

def index
 @comments = current_clinician.comments
end

comment.rb

class Comment < ActiveRecord::Base
 belongs_to :clinician
 belongs_to :patient
end

Solution

  • @comments.map(&:patient) gives objects which are of class Patient, and that is why the links are passing patient_id instead of comment_id.

    You should be using group instead of map here.

    Something along the lines of @comments.group(:patient).. ; the loop syntax has to be changed to work with the output from this scope.

    See http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/group for more details about how group works.