ruby-on-railsassociationsclearance

How to display a user's posts only. Not others


This app is for tutors. When a tutor finishes a class, they fill out a class_report. Then the index page should display only their class_reports. Here's my problem: I've made two accounts, test1 and test2. test1 can see both test1 and test2's class_reports but test2 cannot see any posts, not even their own. It is even saying a post was created by test1 when test2 created it.

I'm pretty sure something is off in the index part or create part of the class_reports_controller but I am not entirely sure tbh. I think it could also be in the models as well.

class_reports_controller.rb

class ClassReportsController < ApplicationController
  before_action :require_login
  before_action :set_class_report, only: [:show, :edit, :update, :destroy]

  # GET /class_reports
  # GET /class_reports.json
  def index
    @class_report = current_user.class_reports
  end

def create
    @class_report = ClassReport.new(class_report_params)
    @class_report.user = User.first

    respond_to do |format|
      if @class_report.save
        format.html { redirect_to @class_report, notice: 'Class report was successfully created.' }
        format.json { render :show, status: :created, location: @class_report }
      else
        format.html { render :new }
        format.json { render json: @class_report.errors, status: :unprocessable_entity }
      end
    end
  end

Models:

class_report.rb

class ClassReport < ApplicationRecord
  belongs_to :user
end

user.rb

class User < ApplicationRecord
  include Clearance::User
  has_many :class_reports
  before_save { self.email = email.downcase }
end


Solution

  • There is something wrong in your create action, on this line:

    @class_report.user = User.first

    and change it to:

    @class_report.user = current_user

    So the problem with first line is that all the report is created and link to first user (always), that's why other user doesn't have the reports. By changing to second line, we create a report and link to the logged-in user (current_user), therefore the report is created and assigned to whoever logged-in and create report.

    Hope it help.