如何在Rails管理中显示未范围的模型?

我自己需要这个,所以这里是QA风格:

默认情况下, Rails Admin显示模型的default_scope。 如何让它显示每个完全没有结合的模型?

方法1

如果只需要列出记录,则可以使用scopes方法来控制返回哪些记录。 第一个数组元素是默认值,因此如果您将以下内容添加到初始化器中:

list do scopes [:unscoped] end 

你会看到所有的记录。

方法2

如果您想要列出更多列表模型,则可以创建虚拟轨道管理模型。 例如,假设您有一个带有布尔存档标志的Post模型:

 class Post < ActiveRecord::Base default_scope { archived: false } end 

您可以创建一个在rails_admin中使用的虚拟模型(在app / models / rails_admin中)

 class RailsAdmin::Post < ActiveRecord::Base self.table_name = "posts" end 

然后,配置rails_admin以使用RailsAdmin :: Post,并且所有post都将是未作用域的。

将此Monkey补丁添加到rails admin初始化程序中:

 ### Monkey pactch for unscoped records in admin panel require 'rails_admin/main_controller' module RailsAdmin class MainController alias_method :old_get_collection, :get_collection alias_method :old_get_object, :get_object def get_collection(model_config, scope, pagination) old_get_collection(model_config, model_config.abstract_model.model.unscoped, pagination) end def get_object raise RailsAdmin::ObjectNotFound unless (object = @abstract_model.model.unscoped.find(params[:id])) @object = RailsAdmin::Adapters::ActiveRecord::AbstractObject.new(object) end end end 

取自https://github.com/sferik/rails_admin/issues/353 。

我有一个类似于Charles’的解决方案,但猴子修补了模型层而不是控制器层。 这可能在Rails Admin版本中更稳定,但是特定于ActiveRecord并且不会影响Mongoid,尽管原理很容易应用于其他适配器。

再次,将它放在rails admin初始化程序中。

 # # Monkey patch to remove default_scope # require 'rails_admin/adapters/active_record' module RailsAdmin::Adapters::ActiveRecord def get(id) return unless object = scoped.where(primary_key => id).first AbstractObject.new object end def scoped model.unscoped end end 

我的猴子补丁,对于Mongoid:

 module RailsAdminFindUnscopedPatch def get(id) RailsAdmin::Adapters::Mongoid::AbstractObject.new(model.unscoped.find(id)) rescue super end end RailsAdmin::Adapters::Mongoid.prepend(RailsAdminFindUnscopedPatch) 

我正在重复使用原始救援条款( super电话)。