LoginSignup
12
8

More than 5 years have passed since last update.

Active Adminにスコープを追加する

Posted at

はじめに

Active Adminというgemを利用すると、Ruby on Railsアプリケーションに管理画面を簡単に追加することができます。

Active Adminの機能の1つにスコープがあります。
スコープを定義しておくことでスコープ内のコレクションを絞り込んで表示することができます。

簡単な商品データベースを例にスコープを追加します。
Active Adminのセットアップは省略します。

テーブル名はproductsです。
テーブルの定義は以下のとおりです。

create_products.rb
class CreateProducts < ActiveRecord::Migration
  def self.up
    create_table :products do |t|
      t.string :name
      t.integer   :price
      t.boolean :published
      t.timestamps
    end
  end
end
物理名 論理名
name 商品名 string
price 価格 integer
published 公開 boolean

以下のファイルをapp/models配下に作成します。

product.rb
class Product < ActiveRecord::Base
end

以下のファイルをapp/adminに作成します。

product.rb
ActiveAdmin.register Product do
    permit_params :name, :price, :published
end

以下のようにデータを登録しました。

1

id name price published
1 テレビ 40000 NO
2 掃除機 30000 NO
3 洗濯機 50000 YES

Active Adminではboolean型はYES、NOで表示されます。

スコープを追加する

商品が公開(publishedがYES)のものを絞り込むためのスコープを追加します。

以下のファイルをapp/admin/product.rbに追記します。

product.rb
ActiveAdmin.register Product do
    permit_params :name, :price, :published

    scope :published do |products|
            products.where(:published => true)
    end
end

以下の画像のように「Published (1)」が表示されます。1というのは条件に該当するのが1件という意味です。

2

「Published (1)」をクリックすると以下の画像のように1件のみ表示されます。

3

すべて表示するためのスコープはscope "All", :all, :default => trueと記述します。

product.rb
ActiveAdmin.register Product do
    permit_params :name, :price, :published

    scope "All", :all, :default => true
    scope :published do |products|
            products.where(:published => true)
    end
end
12
8
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
12
8