ruby-on-rails - 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
解决方案
而不是试图传递用户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
推荐阅读
- google-bigquery - How to manipulate a query for 'Average Session Duration' to 'Average Session Duration by DAU' using Google Analytics in BigQuery?
- reactjs - 我对 React 中的 onChange 事件有疑问
- google-chrome-extension - Chrome extension transparent background and rounded corners (like Save To Pocket)
- python - How overwrite Django Admin readonly FileFields HREF url
- java - How to use variable obtained from a parse method in onCreate
- javascript - Add external libraries in Angular 8
- algorithm - What Data structure/Algorithm should I use - interview question
- azure-devops - 用于 Azure DevOps 的带有 azure-pipelines.yml 的 SpecFlow 示例
- python - 通过将 OAuth 2.0 与 Azure Active Directory 和 API 管理结合使用来保护 API
- android - 如何有效地在android应用程序中实现短按和长按(或长按)?