添加默认范围

时间:2018-10-25 09:01:42

标签: ruby-on-rails activeadmin

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

我正在这样向模型添加default_scope

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

并且我可以在其他操作(例如unscopeshoweditupdate)中使用delete

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

代替:

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

覆盖默认范围的行为。

是否有任何 ActiveAdmin Rails 方法将默认范围 应用于index

我正在使用ActiveAdmin。

将来我可能会添加更多操作,只需要对它们应用默认范围,因此我正在寻找一种更短,更紧凑的解决方案。

2 个答案:

答案 0 :(得分:1)

好的,我希望有一个简单帮助程序,我可以将其用于将默认作用域仅应用于某些操作。但是,相反,我最终添加了一个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会注意!

答案 1 :(得分:0)

您可以为此使用名为@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

似乎是一个可行的解决方案-怎样满足您的要求?

相关问题