繁体   English   中英

如何仅显示用户的帖子。 没有其他

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM