首页 > 解决方案 > Ruby - 如何在模型中获取当前用户?

问题描述

我想列出当前用户对本书的评论并等待批准。我试过 where(user_id: current_user.id) 但它不起作用。如何在模型中使用 current_user?

版本:Rails 6

评论模型。

class Comment < ApplicationRecord
  validates :title, presence: true
  validates :content, presence: true

  belongs_to :book
  belongs_to :user

  scope :approved, -> {where(status: true)}
  scope :waiting_for_approval, -> {where(status: false).where(user_id: current_user.id)}
end

用户模型

class User < ApplicationRecord
  before_create :set_username
  
  has_many :books
  has_many :comments
  has_many :offers

  validates_length_of :set_username, 
  :minimum => 5, :maximum => 50, 
  presence: true,
  uniqueness: true
 
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  def set_username
    self.username = self.email.split(/@/).first
  end
end

图书模型

class Book < ApplicationRecord
  validates :title, presence: true
  validates :author, presence: true

  belongs_to :user
  has_many :comments
  has_many :offers

  scope :can_be_listed, -> {where(status: true)}
  scope :can_be_tradable, -> {where(status: true, tradable: true)}
end

标签: ruby-on-railsruby

解决方案


而不是试图传递用户ID,这实际上只是用户模型上的一个简单关系

class Comment < ApplicationRecord
  scope :waiting_for_approval, -> { where(status: false) }
end

class User < ApplicationRecord
  has_many :comments
end

然后你可以在你的控制器或视图中等待当前用户的批准......作为

current_user.comments.waiting_for_approval

推荐阅读