开发者

how do i get the "current_user" in a "visible do" block in config/initializers/rails_admin.rb

开发者 https://www.devze.com 2023-03-19 16:40 出处:网络
I\'m trying to implement something similar to this: RailsAdmin.config do |config| config.model Team do list do

I'm trying to implement something similar to this:

RailsAdmin.config do |config|
  config.model Team do
    list do
      field :name
      field :created_at
      field :revenue do
        visible do
          current_user.roles.include?(:accounting) # metacode
        end
      end
    end
  end
end

I know in the README it says the exampl开发者_如何学编程e is theoretical, but I keep getting that current_user is not found within that block. I'm authorizing with CanCan:

RailsAdmin.authorize_with :cancan

At the top of rails_admin.rb in config/initializers

Can anyone tell me how to get current_user available within the visible block? I'd like to only show certain fields in the "List" view if a user is an admin.


Since current_user is included as a helper in the view, you can get it through the bindings hash:

visible do
  bindings[:view].current_user.has_role? :admin # This works for Devise
end

I got the idea from this other question: How to set the user to current_user when creating a new model using rails_admin

More info about rails_admin bindings in its wiki: https://github.com/sferik/rails_admin/wiki/Railsadmin-DSL

Hope it helps.


Initializers are run once on application startup, so I don't think you can get a current user from within an initializer like this.


I have not tried this myself, but you may find this useful:

https://github.com/sferik/rails_admin/issues/559

In short, define RailsAdmin::Config.current_user_method in the rails_admin initializer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号