1
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?

【Rails】親子関係になっているデータのフォーム送信について

Posted at

記事概要

Ruby on Railsで、親子関係になっているデータをフォームで登録する方法についてまとめる

前提

  • Ruby on Railsでアプリケーションを作成している
  • 親子関係でテーブル設計を行っている

サンプルアプリ(GitHub)

手順

  1. ネスト構造でルーティングを設定する
    config/routes.rb
    Rails.application.routes.draw do
      root to: 'organizations#index'
      resources :organizations, only: :index do
        resources :members, only: [:index, :new, :create]
      end
    end
    
  2. 子要素のコントローラーに、newアクションとcreateアクションを追加する
    app/controllers/members_controller.rb
    class MembersController < ApplicationController
      def new
        # paramsに含まれているorganization_idを代入
        @organization = Organization.find(params[:organization_id])
        # Memberモデルのインスタンス情報を代入
        @member = Member.new
      end
    
      def create
        # paramsに含まれているorganization_idから、メンバーが所属する組織のレコードを取得
        @organization = Organization.find(params[:organization_id])
        # 上記組織(Organization)に紐づくMemberモデルのインスタンスを生成し、属性値を指定
        @member = @organization.members.new(member_params)
        # インスタンスを保存
        @member.save
        # メンバー一覧画面に画面遷移
        redirect_to organization_members_path(@organization)
      end
    
      private
      def member_params
        params.require(:member).permit(:name)
      end
    end
    
  3. 子要素のnew画面(app/views/members/new.html.erb)にフォームを追加する
    <%= form_with model: [@organization, @member], local: true do |f|%>
      <%= f.text_field :name %>
      <%= f.submit '送信' %>
    <% end %>
    

form_withメソッド

1
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
1
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?