LoginSignup
1
0

More than 3 years have passed since last update.

ActiveAdminのassociation検索カスタムがついにできた

Posted at

要約

  • modelのscopeで検索できた!
  • ので、応用範囲が広い(これだけ覚えておけばfilterのカスタム全部いけそう)
  • ActiveAdminのカスタムはなかなかググりづらい
  • associatedなmodelのカラムを文字列で検索する
  • 最新情報(2019/10/10時点)
  • 基本的にこの記事方法でできる
  • stringで検索するには

やり方

この記事の方法でできること確認しました(2019/10/10時点)
ありがとうございます!
具体的には

  • 引数一つでmodelにscopeつくる
  • self.ransackable_scopes の中でそのscopeを渡す
  • admin/model_namesの中でfilter :scope_name, as: :string

元記事になかった注意点として、
- as: :stringactiveadminドキュメントで書いてある、filterに使いたいクラスを指定する。指定しないとfilter自体が出てこない。(多分scopeだから自動判定できないため)
- activeadmin_addons gemを使ってる人は、as: :search_select_filter使うとエラーになる

なにがうれしいか

activeadminて独自の記法が多くて、ドキュメントされてないことが多いと思っているので、独自記法関係なくscope使ってそのまま検索できる方法がわかったのはうれしい

class Post < ApplicationRecord
  has_many :authors, through: :...
  scope :created_by_author_profile_name, -> (author_profile_name) {
    # 検索ロジック
  }

  def self.ransackable_scopes(_auth_object = nil)
    %i(created_by_author_profile_name)
  end
end

ActiveAdmin.register Post do
  filter :created_by_author_profile_name, as: :string
end
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0