これまでに作った機能について簡単にまとめていく。
今回は、
子モデルの同時作成・更新
使用モデル
Blogモデル
カラム | データ型 | |
---|---|---|
1 | title | string |
2 | content | text |
Articleモデル(アソシエーションは記事中で追加)
カラム | データ型 | |
---|---|---|
1 | title | string |
2 | content | text |
3 | blog_id | bigint |
外部キーの追加
1 |
$ rails g migration AddBlogRefToArticles blog:references |
アソシエーションの設定
app/models/blog.rb
1 2 3 |
class Blog < ActiveRecord::Base has_many :articles, dependent: :destroy end |
app/models/article.rb
1 2 3 |
class Article < ActiveRecord::Base belongs_to :blog end |
accepts_nested_attributes_forの設定
app/models/blog.rb
1 2 3 4 |
class Blog < ActiveRecord::Base has_many :articles accepts_nested_attributes_for :articles, allow_destroy: true end |
コントローラーの設定
app/controllers/blogs_controller.rb
1 2 3 4 5 6 7 8 9 10 11 12 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<%= 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を使用
以上で作成完了