简体   繁体   English

将Rails 4 current_user(gem devise)访问模型

[英]Rails 4 current_user (gem devise) acess into model

I would like add condition in my model (ForumsTopic) and i need the current user value. 我想在我的模型(ForumsTopic)中添加条件,我需要当前的用户值。

Here's my ForumsTopic.rb : 这是我的ForumsTopic.rb:

class ForumsTopic < ActiveRecord::Base
 belongs_to :forum
 belongs_to :user
 has_one :topic_track, ->(user){where(user_id: current_user.id)}, :class_name=> 'ForumsTrack'
 has_many :forums_messages

on the line with "has_one :topic_track[...] i have one condition with user_id = current_user.id. 在“ has_one:topic_track [...]”这一行上,我有一个条件,其中user_id = current_user.id。

But, how i can make that ? 但是,我该怎么做呢?

I'd use a scope for that in the ForumsTrack model. 我会在ForumsTrack模型中使用该作用域。

class ForumsTopic < ActiveRecord::Base
  has_one :topic_track, :class_name=> 'ForumsTrack'
end

class ForumsTrack < ActiveRecord::Base
  scope :for_user, -> (user) { where(user: user) }
end

I would then pass the current_user from a place it is available (controller, service_model, etc). 然后,我将从可用的地方(控制器,service_model等)传递current_user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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