I am using rails server with rails_admin
I want to add a table to my include_models but I don't want to let write access to one/few of the models:
My admin looks like this:
# frozen_string_literal: true
RailsAdmin.config do |config|
### Popular gems integration
# == Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.actions do
dashboard # mandatory
index # mandatory
new
export
bulk_delete
show
edit
delete
show_in_app
end
config.included_models = %w[ MyModel1
MyModel2]
end
I would like to add something like
config.read_only_models = %w[MyModel3, MyModel4]
Any suggestion?
I've divided my answer to 2 sections as it may apply to different scenarios:
General case:
General behaviour can be set by adding a readonly?
method for the model(s).
If the value is set to true
, attempting to update a record will result in an error.
See here for more details.
def readonly?
true
end
ActiveRecord's underlying persistence will check readonly?
before creating or updating any records.
You can also add dynamic content inspection such as:
def readonly?
read_only_list.include? (self.class.name)
end
RailsAdmin specific behaviour (2nd scenario):
If you want to set a specific behaviour for RailsAdmin, you can create a special role and then use CanCanCan which is an authorization library which restricts what resources a given user is allowed to access.
It can also restrict RailsAdmin & grant access using an Ability
class which defines different permissions depending upon the user's role.
See an example how to Use different Ability classes for front-end and admin
You need to do it on the rails admin model configuration to have access to the current user. I'm afraid this rules out doing it at the RailsAdmin.config level.
You'll need to do it then field by field.
class MyModel3 < ApplicationRecord
rails_admin do
configure :field do
read_only do
bindings[:view].current_user.admin?
end
end
configure :field2 do
read_only do
bindings[:view].current_user.admin?
end
end
configure :field3 do
read_only do
bindings[:view].current_user.admin?
end
end
# ...
end
end
Not ideal but you'll see that is impossible with the current implementation of the actions by taking a look at the code of the edit action that inherits from base .
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.