はじめに
一瞬でめちゃイケてる管理画面を作ってくれるrails_admin
今までCRUDそれぞれ画面編集してたのはなんだったんだ……と思う完成度です。
しかし、多対多の関連付けの時、毎回のようにエラーが出ました。
出たエラー
ActiveRecord::HasManyThroughOrderError in RailsAdmin::Main#edit
原因
色々試しましたが、Modelでの関連付け設定の順番が原因でした。
構成
タイトルごとに複数のタグ。
タグごとに複数のタイトル。
title has_many tags
tag has_many titles
これを実現させるために、tag_mapsというテーブルを間に挟んでいます。
[tag_maps]
id
title_id
tag_id
解決したコード
model/title.rb
class Title < ApplicationRecord
has_many :tag_maps
has_many :tags, through: :tag_maps
end
model/tag_map.rb
class TagMap < ApplicationRecord
belongs_to :title
belongs_to :tag
end
model/tag.rb
class Tag < ApplicationRecord
has_many :tag_maps
has_many :titles, through: :tag_maps
end
ただ普通に記述してるだけなのですが、なぜか順番が逆だとエラーが出ました。
オマケの注意点
今回のこれは、Rails5での解決策でした。
(Rails 5.2.4.2)
他のバージョンでは、ここ見たら参考になるかも……?
https://github.com/sferik/rails_admin/wiki/Associations-basics
あとrails_adminの編集画面で若干表示項目が変に見えるのは……まぁええでしょ。エラー出てないし
終わり