【问题标题】:Adding a default scope添加默认范围
【发布时间】:2018-10-25 09:01:42
【问题描述】:

我希望将默认范围应用于模型中的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。

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

【问题讨论】:

  • 为什么不在索引操作中应用这个范围?
  • @Ilya 我将来可能会添加更多操作,我只需要将默认范围应用于这些操作,因此我正在寻找更短的解决方案。
  • 我能想到的最简洁的方法是在您的控制器中使用一个单独的“收集”方法,并使用一个之前的操作将您想要的范围应用于给定操作的该集合。鉴于模型不知道它在哪个控制器操作中,我看不到直接从模型文件中执行此操作的方法。
  • @Mark 感谢您的评论。我最终考虑了您的方法,最终结果是简洁紧凑的解决方案 :)
  • 不用担心 - 本来打算写这样的东西,但今天我的老板和我在办公室,所以不得不等到午餐 :)

标签: ruby-on-rails activeadmin


【解决方案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 将负责!

【讨论】:

    【解决方案2】:

    您能否为此使用名为 @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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多