添加默认范围

Adding a default scope

我希望默认范围应用于模型中的index操作。

我将 default_scope 添加到模型中:

default_scope { where(:status => "Active") }

我可以在其他操作中使用 unscope(即 showeditupdatedelete),如下所示:

@beacon = Beacon.where(id: params[:id]).unscope(where: :status).first

而不是:

@beacon = Beacon.find(params[:id]

覆盖默认范围的行为。

是否有任何ActiveAdminRails方法来应用默认范围 只有index?

我正在使用 ActiveAdmin。

我将来可能会添加更多操作,只有我需要应用默认范围的操作,所以我正在寻找一个更短和紧凑的解决方案

您可以为此使用一个名为 @scoped 或类似的集合吗?

例如:

ACTIONS_WITH_DEFAULT_SCOPE = ['index']

before_action :set_scoped_collection

...

def set_scoped_collection
  @scoped = if action_name.in?(ACTIONS_WITH_DEFAULT_SCOPE)
    Beacon.where(status: "Active")
  else
    Beacon.all
  end
end

# or the otherway round, using `unscope`
def set_scoped_collection
  @scoped = if action_name.in?(ACTIONS_WITH_DEFAULT_SCOPE)
    Beacon.all
  else
    Beacon.unscope(where: :status)
  end
end

似乎是一个可行的解决方案 - 它如何满足您的要求?

好的,我希望可以有一个简单的助手,我可以用它来将默认范围应用到某些动作。但相反,我最终添加了一个 before_action,它将仅获取某些操作的 unscoped 记录。

before_action :set_unscoped_beacon_variables, only: [:show, :edit, :update, :destroy]

def set_unscoped_beacon_variables
  @beacons = Beacon.unscope(where: :status)
  @beacon = Beacon.where(id: params[:id]).unscope(where: :status).first
end

这样,我可以将更多此类操作添加到 before_action 列表中,对于其余操作(需要默认范围),default_scope 会处理!