2
2

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.

親子のActiveModelをformに適用する

Posted at

ActiveModelを使用し、子要素もモデル化したい場合、下記のように記述するとpostパラメータとして引き回しできます。

Modelの定義

parent_model.rb
# 親Model
class ParentModel
  # 子モデルの保持領域
  attr_accessor :child_models

  # ActiveRecordのaccepts_nested_attributes_for 相当の処理
  def child_models_attributes=(attributes)
    @child_models ||= []
    attributes.each do |_, params|
      @child_models.push(ChildModel.new(params))
    end
  end
end
child_model.rb
# 子Model
class ChildModel
  attr_accessor :field
end

コントローラーの定義
※StrongParameterの定義に少々癖があります。

sample_controller.rb
class SampleController < ApplicationController
  def input
    @parent_model = ParentModel.new(
          child_models:[ChildModel.new,ChildModel.new]
      )
  end
  def save
    parent_model = ParentModel.new(post_params)
  end

  private
  # strongparamの定義
  def post_params
    params.require(:parent_model).permit(
        child_models_attributes: [
            :field
        ]
    )
  end
end

Viewの定義

sample.html.haml
.main
  .section
    = form_for @parent_model,  url: {action: 'save'} do |f|
      - @parent_model.child_models.each_with_index do |form, index|
        = f.fields_for :child_models, form do |fields|
          = fields.hidden_field :field
          %br
          %h2 #{1 + index}人目

設定に誤りがなければ下記のように配列としてtagが展開されます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?