ActiveAdminの改造集

Railsを使うにあたってActive Adminを管理画面に多用しているのですが、ネットになかなか有益な情報が落ちてなかったので、自分が使うやつはまとめてみよう、と思って記事を書いてみました🙌

使えそうなやつ

Modelに紐づかないページ作成

モデルに紐づかないページを作成したいケースでは、下記のように使い分けることでページ作成が可能です

# OK
ActiveAdmin.register 'Order' do
end

# NG
ActiveAdmin.register_page 'Order' do
end

ちなみに中身はcontentで囲んでtableやcolumnなどで表示が可能です

content title: proc { I18n.t('active_admin.dashboard') } do
    table_for Order.all do
      column "user",     :user
      column "レク", :recreation
      # column "Amount",          :amount_in_dollars
    end
    columns do
      column do
        panel 'Recent Posts' do
          ul do
            Order.all.map do |order|
              # li link_to(post.title, admin_post_path(post))
              li order.user
            end
          end
        end
      end
    end
  end

Showのattributes_table_forでlink_to入れたい時

レシーバーに書くデータを突っ込むことで、partner.recreations[n] を取得できる

show do
  attributes_table_for partner.recreations do
    row :title
    row :id do |rec| # ここ!!
      link_to '詳細', admin_recreation_path(rec.id)
    end
  end
end

カスタムなHTMLを入れたい場合

部分テンプレ作って作成するのが吉です

一応elmとかっぽく記述も可能ですが、htmlの方が誰でもわかりやすいかと思うので、こんな感じで作成すると良いかと

テンプレは /views/admin/_chat.html.erb を作成して差し込んでます

show do
    attributes_table do
      row :id
      row :user
      row :recreation
      row :prefecture
      row :city
      row :number_of_people
      row :order_type

      row :created_at
      row :updated_at
    end

    panel 'チャット', style: 'margin-top: 30px;' do
      render 'admin/chat', order: order # 複雑な内容を表示したいので、テンプレ作成して対応
    end
  end

参考記事

ActiveAdmin Forms and date select inputs with Custom Pages

undefined method `update_attributes’ for #User:0x00007fcd2f4ab678

rails6.1ではupdateに変更する必要があるみたいです

# NG
def update_without_current_password(params, *options)
    params.delete(:current_password)
    if params[:password].blank? && params[:password_confirmation].blank?
      params.delete(:password)
      params.delete(:password_confirmation)
    end
    result = update_attributes(params, *options)
    clean_up_passwords
    result
  end

## OK
def update_without_current_password(params, *options)
    params.delete(:current_password)
    if params[:password].blank? && params[:password_confirmation].blank?
      params.delete(:password)
      params.delete(:password_confirmation)
    end
    result = update(params, *options) # 修正
    clean_up_passwords
    result
  end

参考記事

undefined method `update_attributes’ と言われたら

axiosで401のinterceptorを実装

401返ってきたときに自動的にtoken取得するためのコードを実装しました

const instance = (): AxiosInstance => {
  const headers: { [key: string]: string } = { 'Content-Type': 'application/json' };
  const ax = axios.create({baseURL: API_PATH, timeout: 15000, headers });

  ax.interceptors.response.use((response) => response, async (error) => {
    const originalRequest = error.config;
    // eslint-disable-next-line no-underscore-dangle
    if (error.response.status === 401 && !originalRequest._retry) {
      // eslint-disable-next-line no-underscore-dangle
      originalRequest._retry = true;
      // eslint-disable-next-line no-underscore-dangle
      await refreshToken(); // ここでtokenをrefresh
      ax.defaults.headers.common.Authorization = `Bearer ${getToken()}`; //getToken()はstringのtokenをreturnする関数。これは書き換えてください
      return ax;
    }
    return Promise.reject(error);
  });
  return ax;
};

参考記事

Using Axios interceptors for refreshing your API token.

Illegal base64 data at input byte 4 when using base64.StdEncoding.DecodeString(str)

フロントから送信されてきたbase64のstringをgoのサーバーで受けていたところタイトルのエラーが発生

問題点はdata: ~~~ の部分が入っているから、とのことだったので、下記のように修正を加えることで、解決することができました🙌

input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA"

b64data := input[strings.IndexByte(input, ',')+1:]
fmt.Println(b64data)

参考記事

Illegal base64 data at input byte 4 when using base64.StdEncoding.DecodeString(str)

Docker + Go + Ginで”dial tcp 127.0.0.1:5432: connect: connection refused”エラー

db にコンテナ名を入れることで解消できました!

# db部分にはdbのコンテナ名を入れる
conn := "postgres://postgresql:postgresql@db:5432/golang_api?sslmode=disable"

# docker-compose.yml
db:  # ここ!!!!!
    container_name: db
    build:
      context: ./docker/postgres
      dockerfile: Dockerfile
    ports:
      - '5432:5432'
    expose:
      - 5432
    environment:
      POSTGRES_HOST: localhost
      POSTGRES_DB: golang_api
      POSTGRES_USER: postgresql
      POSTGRES_PASSWORD: postgresql
      POSTGRES_PORT: 5432
    volumes:
      - db:/var/lib/postgresql/data

参考記事

Connection refused between docker container of clair and pgsql #134

Go + Gin + Air + M1のDockerfile

シンプルにDockerfile作りたいなと思って実装しました

リポジトリはこちら

https://github.com/hiyashikyuri/go_m1_docker

# Dockerfile
FROM golang:1.16

COPY . /app
WORKDIR /app

RUN go get -u github.com/cosmtrek/air
RUN go mod download

# docker-compose.yml
version: "3"
services:
  app:
    container_name: app
    volumes:
      - ./:/app
    tty: true
    command: "air -c .air.toml"
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8080:8080

参考記事

【Go 言語】 Docker 上 で Gin を動かすまで

Goのnet/httpでform data送る方法

LINE notificationを送信するにあたって、form dataで送信を行なったので、そのコードシェアしておきます

func (line LineNotification) send() {
	token := ""
	uri := "https://notify-api.line.me/api/notify"
	data := url.Values{}
	data.Set("message", line.Message)

	client := &http.Client{}

	req, _ := http.NewRequest("POST", uri, strings.NewReader(data.Encode()))
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

	resp, err := client.Do(req)

	if err != nil {
		log.Fatal(err)
	}

	defer func() {
		err := resp.Body.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()
	fmt.Print("Line message was sent")
}

参考記事

How to make a http url form encoded request in Golang

A source code for Next.js + WordPress

*Translated by deepl.Japanese article is here.

In creating my Jamstack blog, I found few articles and source codes that use WordPress as CMS, so I created one.

“There are a lot of people who have the same thought as I do: “I’m using WordPress, but I want to use the same articles when I migrate to Jamstack! I’m sure there are a lot of people who feel the same way, so please use this code to publish a Jamstack blog while using your existing content!

How to use it

  • Install graphql in existing wordpress according to README (as per official README)
  • Enter the URL in “env” (This is the file. This is a sample, so please create and use .env)
  • Enter the slug and display name for the fixed page (file here)
    • If the slug is wrong, it may not work.

Please do me a favor?

  • Push Star on Github!
  • Buy me a coffee!!
  • Please let me know if there are any modifications.

Source code

If you have any questions, please DM me via Github issue or Twitter.

nextjs_wordpress