[英]How to display a user's posts only. Not others
這個程序是為導師。 輔導員完成課程后,他們會填寫class_report。 然后,索引頁面應僅顯示其class_reports。 這是我的問題:我已經建立了兩個帳戶,test1和test2。 test1可以看到test1和test2的class_reports,但是test2不能看到任何帖子,甚至看不到它們的帖子。 甚至說test2在創建帖子時是由test1創建的。
我很確定索引部分有問題,或者創建了class_reports_controller的一部分,但是我不確定tbh。 我認為也可以在模型中。
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
楷模:
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
在這一行上,您的create
動作有問題:
@class_report.user = User.first
並將其更改為:
@class_report.user = current_user
因此,第一行的問題是所有報表都已創建並鏈接到(始終)到第一位用戶,這就是為什么其他用戶沒有該報表的原因。 通過更改為第二行,我們創建一個報告並鏈接到已登錄的用戶(current_user),因此將創建該報告並將其分配給任何登錄並創建報告的人。
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.