简体   繁体   中英

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.

Here's my 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.

But, how i can make that ?

I'd use a scope for that in the ForumsTrack model.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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