これまでに作った機能について簡単にまとめていく。
今回は、
子モデルの同時作成・更新
使用モデル
Blogモデル
| カラム | データ型 | |
|---|---|---|
| 1 | title | string |
| 2 | content | text |
Articleモデル(アソシエーションは記事中で追加)
| カラム | データ型 | |
|---|---|---|
| 1 | title | string |
| 2 | content | text |
| 3 | blog_id | bigint |
外部キーの追加
$ rails g migration AddBlogRefToArticles blog:references
アソシエーションの設定
app/models/blog.rb
class Blog < ActiveRecord::Base has_many :articles, dependent: :destroy end
app/models/article.rb
class Article < ActiveRecord::Base belongs_to :blog end
accepts_nested_attributes_forの設定
app/models/blog.rb
class Blog < ActiveRecord::Base has_many :articles accepts_nested_attributes_for :articles, allow_destroy: true end
コントローラーの設定
app/controllers/blogs_controller.rb
class BlogsController < ApplicationController
def new
@blog = Blog.new
1.times { @blog.articles.build }
end
def blog_params
params.require(:blog).permit(:title, :text, article_attributes: %I(title content))
end
end
articleのフォームを1つに設定
_attributesでarticleのパラメーターを設定
フォームの作成
app/views/blogs/_form.html.erb
<%= nested_form_for(blog) do |f| %>
<div class=“blog_form">
<%= f.label :itle %>
<%= f.text_field :title %>
<%= f.label :content %>
<%= f.text_field :content %>
</div>
<div class=“article_form">
<%= f.fields_for :articles do |article| %>
<%= article.label :title %>
<%= article.text_field :title %>
<%= article.label :content %>
<%= article.text_field :content %>
<% end %>
</div>
<div class="action">
<%= f.submit %>
</div>
<% end %>
nested_form_forを使用
以上で作成完了
