0
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】モデル間の関連付けにおけるbuildメソッドとストロングパラメータの書き方

Last updated at Posted at 2025-04-11

はじめに

Active Recordの関連付けのケースごとに、buildメソッドの書き方と、ストロングパラメータの書き方について調べた学習記録です。

一対一の場合

モデルでの定義

class Author < ApplicationRecord
  has_one: account
end
class Account < ApplicationRecord
  belongs_to: user
end

buildメソッドによる関連付けの定義

@user = User.new
@account = @user.build_account

ストロングパラメータの定義方法

  • accepts_nested_attributes_for の追加
class User < ApplicationRecord
  has_one: account
  accepts_nested_attributes_for :account # 追加
end
private
def user_params
  params.require(:user).permit(:email, # usersテーブルへの保存を許可するキー名
   account_attributes: [:first_name, # accountsテーブルへの保存を許可するキー名
   ])
end

一対多の場合

モデルでの定義

class User < ApplicationRecord
  has_many: accounts
end
class Account < ApplicationRecord
  belongs_to: user
end

buildメソッドによる関連付けの定義

@user = User.new
@account = @user.accounts.build

ストロングパラメータの定義方法

  • accepts_nested_attributes_for の追加
class User < ApplicationRecord
  has_many: accounts
  accepts_nested_attributes_for :accounts # 追加
private
def user_params
  params.require(:user).permit(:email, # usersテーブルへの保存を許可するキー名
   accounts_attributes: [:first_name, # accountsテーブルへの保存を許可するキー名
   ])
end

多対多の場合

モデルでの定義

class Account < ApplicationRecord
  has_many :user_accounts
  has_many :users, through: :user_accounts
end
class User < ApplicationRecord
  has_many :user_accounts
  has_many :accounts, through: :user_accounts
end
class UserAccount < ApplicationRecord
  belongs_to :user
  belongs_to :account
end

buildメソッドによる関連付けの定義

@user = User.new
@account = @user.accounts.build # 中間テーブルにも自動で反映される

ストロングパラメータの定義方法

private
def user_params
  params.require(:user).permit(:email, # usersテーブルへの保存を許可するキー名
  account_ids: [] # コントローラーに渡るidの配列と中間テーブルを作成する
  )
end
0
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
0
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?