[英]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. 辅导员完成课程后,他们会填写class_report。 Then the index page should display only their class_reports. 然后,索引页面应仅显示其class_reports。 Here's my problem: I've made two accounts, test1 and test2. 这是我的问题:我已经建立了两个帐户,test1和test2。 test1 can see both test1 and test2's class_reports but test2 cannot see any posts, not even their own. test1可以看到test1和test2的class_reports,但是test2不能看到任何帖子,甚至看不到它们的帖子。 It is even saying a post was created by test1 when test2 created it. 甚至说test2在创建帖子时是由test1创建的。
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. 我很确定索引部分有问题,或者创建了class_reports_controller的一部分,但是我不确定tbh。 I think it could also be in the models as well. 我认为也可以在模型中。
class_reports_controller.rb 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_report.rb
class ClassReport < ApplicationRecord
belongs_to :user
end
user.rb user.rb
class User < ApplicationRecord
include Clearance::User
has_many :class_reports
before_save { self.email = email.downcase }
end
There is something wrong in your create
action, on this line: 在这一行上,您的create
动作有问题:
@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. 通过更改为第二行,我们创建一个报告并链接到已登录的用户(current_user),因此将创建该报告并将其分配给任何登录并创建报告的人。
Hope it help. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.