uzaif
uzaif

Reputation: 3531

fetching logged in user associated record in rails_admin

I have installed rails_admin gem without any error its display models crud too,but i have requirement in which i need to show current_user logged in associated data

e.g User has many Books so in rails admin i want only that user book but currently it's showing all users books which is default behaviour of rails_admin

i have also try to use cancancan gem for achieve same thing but its not working my rails_admin initializers config as below

rails_admin.rb
RailsAdmin.config do |config|
  ### Popular gems integration
  ## == Devise ==
   config.authenticate_with do
    warden.authenticate! scope: :user
   end
   config.current_user_method(&:current_user)
   config.parent_controller = 'ApplicationController'
  ## == Cancan ==
  config.authorize_with :cancan,UserAbility
  ## == Pundit ==
  # config.authorize_with :pundit
  config.included_models = ["Book","User"]
  config.actions do
    dashboard                     # mandatory
    index                         # mandatory
    new
    export
    bulk_delete
    show
    edit
    delete
    show_in_app
  end
end

UserAbility Class is implemented as below

  class UserAbility
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
       if user.present?
         can :access, :dashboard
         can :manage, :Book,id:user.id
       end
  end
end

Upvotes: 3

Views: 978

Answers (2)

gwcodes
gwcodes

Reputation: 5690

Instead of can :manage, :Book,id:user.id, try using:

can :read, Book, user_id: user.id

So the abilities together look like:

can :access, :rails_admin
can :dashboard
can :read, Book, user_id: user.id

Upvotes: 3

Makoto
Makoto

Reputation: 106400

I think you're misunderstanding the scope of Rails Admin. In essence, it's a snapshot of your database, and is meant for more administrative operations like querying your database for something specific.

The only thing you'd reasonably be able to do is to look up all Books for a given user, with the default falling to all books for all users. Filters exist within the display to be able to narrow down based on a user's specific credentials, such as user name, email, or ID.

For a conceptual check, a user in Rails Admin isn't treated or regarded the same as a user in your application. Instead, think of using Rails Admin as a way to check the data in your database as opposed to showing data for a specific, authenticated person.

As you describe, the more appropriate Rails way to do this would be to create a controller and route for this data, and to simply use current_user.books to get all of the books for the current user.

Upvotes: 2

Related Questions