我自己需要这个,所以这里是QA风格:
默认情况下,Rails Admin显示模型的default_scope。如何让它显示每个完全没有范围的模型?
答案 0 :(得分:12)
方法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,并且所有帖子都将是未作用域的。
答案 1 :(得分:5)
将此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
答案 2 :(得分:3)
我有一个类似于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
答案 3 :(得分:0)
我的猴子补丁,对于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
来电)。