2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveAdminでPOSTパラメータを加工してUpdateするメモ

Posted at

問題

  • ActiveAdminで簡単に管理画面を作りたい
  • PostgreSQL特有のデータ型はがないので自作する必要がある
    • 本当はformをいじるなりしてデータ作成出来るようにするほうが良いと思われる
  • Formtastic::Inputs(および付随するjs/css)を書く手間をかけたくない
    • そうだActiveAdmin側のcontrollerを変更しよう

注意点とか?

  • ActiveAdmin.register Post do ... endとするとAdmin::PostContollerが定義されている
    • その中でcontollerを定義すればオーバーライドできる
  • resource_paramsはArrayにActionController::Parametersが入っていた
    • 未確認:複数インスタンスを扱うため?

サンプルコード

app/admin/post.rb
ActiveAdmin.register Post do 
  permit_params :uid, :name, :meta, :related_ids

  form do |f|
    f.semantic_errors # shows errors on :base
    f.inputs do
      f.input :uid
      f.input :name
      f.input :meta,         as: :text    # json,jsonb型をtextとして扱う
      f.input :related_uids, as: :string  # arrayをstringとして扱う
    end
    f.actions
  end # form
 
  controller do
    # 既メソッドを利用してパラメータを加工する
    # https://github.com/activeadmin/inherited_resources/blob/46493ce10fc7d9f0bcd753f5d298c67ca83cf9b0/lib/inherited_resources/base_helpers.rb#L316
    # https://github.com/activeadmin/inherited_resources/blob/46493ce10fc7d9f0bcd753f5d298c67ca83cf9b0/lib/inherited_resources/base_helpers.rb#L356
    def nomralized_params
      resource_params.map{ |p|
        p.merge(
          related_uids: p[:related_uids].split.map{&:to_i}
        )
      }
    end

    # メソッドをオーバーライドする
    # https://github.com/activeadmin/inherited_resources/blob/46493ce10fc7d9f0bcd753f5d298c67ca83cf9b0/lib/inherited_resources/actions.rb#L42
    def update(options={}, &block)
      object = resource
      if update_resource(object, nomralized_params)
        options[:location] ||= smart_resource_url
      end

      respond_with_dual_blocks(object, options, &block)
    end
  end

end
2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?