Current attribute. Access current_user from model
Current attribute support to set Current.user per request:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_current_user, if: :user_signed_in?
private
def set_current_user
Current.user = current_user
end
end
#app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :user
end
- Now you can get current_user through Current.user in a view or get current_user in a model.
#static_pages/landing_page.html.erb
<%= Current.user.username %>
#app/models/post.rb
class Post < ApplicationRecord
belongs_to :user, default: -> { Current.user }
validates :title, presence: true
end
Read more here:
- [ActiveSupport/CurrentAttributes]https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html){:target=”blank”}
- evilmartians/current-everything
Did you like this article? Did it save you some time?