LoginSignup
3
5

More than 5 years have passed since last update.

ActiveAdminでhas_oneのassociationに対するnestしたフォームを作る

Last updated at Posted at 2017-09-14

has_oneのネストしたフォームをActiveAdminで書いたことがなく、ハマったのでメモ代わりに書きます。

Rails 4以降であれば、以下のように書けます。

親モデルParent、子モデルChildが以下のように定義されているときに、

class Parent < ActiveRecord::Base
  has_one :child
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

ActiveAdminのParentモデルのフォームでは、ヘルパーの:forを使って、以下のように駆ける。(permitなどの記載は省略)

/admin/models/parent.rb
ActiveAdmin.register Parent do
  form do |f|
    f.inputs "子モデルの編集", :for => [:child, f.object.child || Child.new] do |child|
      child.input :hoge
    end
  end

end

:for のところでは、既存のオブジェクトで、すでにchildモデルが設定されていればそれを使い、なければ、Childモデルをnewする、というように書いておく。これで、新規作成時は新しいChildモデルが作られ、更新時は既存のものが使われる。

3
5
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
3
5