Fetching a record in a user related record in rails_admin
I installed the rails_admin
gem without any errors and its display models are red too, but I have a requirement where I need to show the current_user
entered associated data
For example a user has many books, so in rails admin I only want this user book, but currently it shows all user books, which is rails_admin by default
I am also trying to use cancancan
gem to achieve the same goal but my initializer configurator is not working rails_admin
as shown 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
The UserAbility class is implemented 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
source to share
I think you are underestimating the scope of the Rails Admin. Basically, this is a snapshot of your database and is intended for more administrative operations such as querying the database for something specific.
The only thing you could reasonably do is to view everything Book
for a given user, with all books downloaded by default for all users. Filters exist on the display to be able to narrow down based on user credentials such as username, email or ID.
For conceptual validation, the user in Rails Admin is not handled or treated as a user in your application. Instead, consider using Rails Admin as a way to validate data in your database, rather than displaying data for a specific authenticated person.
As you described, a more appropriate Rails way of doing this would be to create a controller and route for that data and just use current_user.books
it to get all the books for the current user.
source to share