5
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 3 years have passed since last update.

rails 1対多 保存の方法 紛らわしいやつまとめ(メモ)

Posted at

1対多のリレーションでも保存の方法の違いが紛らしいな

1番基本

  • 1つ1つリレーションを作るパターン
## リレーション

User 1 - * Post

## user.rb
has_many :posts

## post.rb
belongs_to :user

## controller

def new
  @post = Post.new

def create
  @post = Post.new(post_params)

private

def post_params

  params.require(:post).permit(:name, :body).merge(user_id: current_user.id)

## view
= form_for @post do |form|

  = form.label :title
  = form.text_field :title

  = form.label :body
  = form.text_field :body
  = form.submit '送信'

## 要点

11 userpostの繋がりを作っていくパターン

複数一気に作るパターン

パターン1(子要素のデータがある場合)

  • xx_idsを使う
## リレーション
User 1 - * Skill

## user.rb
has_many :skills

## skill.rb
belongs_to :user


## 子要素のデータ存在する

Skill
  id1 name: "筋トレ"
  id2 name: "イケメン"
  id3 name: "話術"

## controller

def new
  @user = User.new

private

def post_params

  params.require(:post).permit(:name, skill_ids: [])

## view

= form_for @user do |f|
  = f.label :name
  = f.text_field :name  
  = f.fields_for :skill_ids do |skill|
    = skill.collection_select :name, Skill.all, :id, :name  
  = f.submit "送信"

パターン2(子要素のデータがない場合)

  • accepts_nested_attributes_for使う

## リレーション
User 1 - * Address

## user.rb
  has_many :addresses
  accepts_nested_attributes_for :addresses,allow_destroy: true
  
## address.rb
 - state
 - city
 belongs_to :user

## controller

  def new 
    @user = User.new
    @user.addresses.build

  private
  def user_params
      params.require(:user).permit(:name, addresses_attributes: [:id, :state, :city])
    end

## view
= form_for @user do |form|
  .field
    = form.label :name
    = form.text_field :name
  .fidle
    = form.fields_for :addresses do |address|
      = address.label :state
      = address.text_field :state
      = address.label :city
      = address.text_field :city
  .fidle
    = form.fields_for :addresses do |address|
      = address.label :state
      = address.text_field :state
      = address.label :city
      = address.text_field :city

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