0
0

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 3 years have passed since last update.

administrate で refileを使ってファイルを読み込めるようにしたい【rails6】

Last updated at Posted at 2020-09-08

ハードはMacBook Air, 開発環境はVScodeを用いています。
ruby2.6.5
rails6.0.3.2

rails6で管理者gemにadministrate, 画像読み込みgemにrefileを用いた時に, administrateとrefileの連携でハマってしまったので, その詳細と解決方法を紹介します.

ちなみに、administrate_field_refileはrails6に対応していなかったので、使わない方向で頑張りました!

管理者画面(localhost:3000/admin)で, 新しいデータを追加しようとすると, 画像の入力部分がファイル選択ではなく, テキストボックスになってしまっている

localhost:3000/admin へ移動し, 新規Userを作製しようとすると, profile_imageの部分がテキストボックスになっています。(二枚目の画像の一番下)

スクリーンショット 2020-09-08 21.47.03.png
スクリーンショット 2020-09-08 21.47.12.png

そこでこれを解決するために, いろいろ調べてみるとadministrate_field_refileというgemがあるらしいのですが、こちらはrails6に未対応だったので、administrateをカスタムする方向で進めることにしました。

administrateをカスタムする

まず先にadministrate内部のコード、カスタムするであろう部分をローカルで表示できるようにします。administrateのドキュメントを参考に、dashbordのコントローラ, views, fieldを追加していきます。

$ rails generate administrate:dashboard User
$ rails generate administrate:views User
$ rails generate administrate:field refile

次に、dashbordの profile_image_id: Field::String, となっているところを次のように書き換えます。参考;http://administrate-prototype.herokuapp.com/adding_custom_field_types

app/dashboards/user_dashboard.rb
  ATTRIBUTE_TYPES = {
   ~省略~
   profile_image_id: RefileField,
  }.freeze

次にフォームのviewsをテキストボックスからファイルを選択に変更します.

app/views/fields/refile_field/_form.html.erb

<div class="field-unit__label">
  <%= f.label field.attribute %>
</div>
<div class="field-unit__field">
  <%= f.attachment_field :profile_image, direct: field.direct, presigned: field.presigned, multiple: field.multiple %>
</div>

次に, app/fields/refile_field.rbを次のように書き換えます.

app/fields/refile_field.rb
require "administrate/field/base"

class RefileField < Administrate::Field::Base
  def to_s
    data
  end

  def direct
    options.fetch(:direct, false)
  end

  def presigned
    options.fetch(:presigned, false)
  end

  def multiple
    options.fetch(:multiple, false)
  end
end

このままだと、Unpermitted parameters:という赤い文字がコンソールに表示されて画像を設定できないと思うので、以下で許可します。(~~~には, 登録する要素を入れておく。抜けがあると、ターミナルに赤く表示されるので、その都度確認して追加する)

def resource_params
  params.require(:user).permit(:profile_image,:~~~,:~~~,:~~~)
end

恐らくこれでadministrateから画像データを登録できるようになると思います。

パスワードとかも設定できるようにしたい、もっと登録画面を見やすくしたいという人は、以下を参考にしてみてください。
http://blog.319ring.net/2016/05/14/custom_view_administrate/


役に立ったら是非LGTMボタンをポチッと押していただけると嬉しいです:raised_hand_tone1:

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?