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 '送信'
## 要点
1つ1つ userとpostの繋がりを作っていくパターン
複数一気に作るパターン
パターン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