【发布时间】:2020-10-29 12:43:11
【问题描述】:
我想列出当前用户 cmets 写的书并等待批准。我试过 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
【问题讨论】:
-
这能回答你的问题吗? How to get current user in Rails model
标签: ruby-on-rails ruby