shou.com
JP / EN

Rails 登録時に他のモデルも一緒に登録する

Fri Sep 8, 2017
Fri Sep 8, 2017

やりたいこと

記事の作成時に一緒にカテゴリーも作成したい。記事が親でカテゴリーが子の関係です。

rails5を使っています。記事のコントローラやモデルは作成されていて後付けでカテゴリーを追加する時の手順をメモ。

rails 登録時に他のモデルも一緒に登録する

モデル作成

カテゴリーのモデルを作成。

1
$ rails g model category

アソシエーションの設定 atticle.rb

1
2
3
4
5
class Article < ApplicationRecord
  # accepts_nested_attributes_forを使う、
  has_many :categories, dependent: :destroy
  accepts_nested_attributes_for :categories, allow_destroy: true
end

アソシエーションの設定

category.rb、rails5の場合、optional: trueの設定を忘れると動かないので注意!

1
2
3
4
class Category < ApplicationRecord
  # accepts_nested_attributes_forを使う、
belongs_to :article, optional: true
end

schema.rb、categoriesテーブルにarticle_idを持たせる。

1
2
3
4
5
6
create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "article_id"
end

コントローラの設定

articles_controller.rb

newをする時にbuildしてやればいい。親が保存されると子も自動で保存される。

1
2
3
4
5
6
# GET /articles/new
def new
  @article = Article.new
  @article.categories.build
  #2.times { @article.categories.build } 2個作る時はこうする
end

paramsの設定

1
2
3
4
5
6
7
def article_params
      params.require(:article).permit(
      :title,
      :content,
      :editer,
      categories_attributes: [:id, :name])
end

全体は、こんな感じなる。

 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  # GET /articles
  # GET /articles.json
  def index
    @articles = Article.all
    @categories = Category.all
  end

  # GET /articles/1
  # GET /articles/1.json
  def show
  end

  # GET /articles/new
  def new
    @article = Article.new
    @article.categories.build
    #1.times { @article.categories.build }
  end

  # GET /articles/1/edit
  def edit
  end

  # POST /articles
  # POST /articles.json
  def create
    @article = Article.new(article_params)

    respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: 'Article was successfully created.' }
        format.json { render :show, status: :created, location: @article }
      else
        format.html { render :new }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /articles/1
  # PATCH/PUT /articles/1.json
  def update
    respond_to do |format|
      if @article.update(article_params)
        format.html { redirect_to @article, notice: 'Article was successfully updated.' }
        format.json { render :show, status: :ok, location: @article }
      else
        format.html { render :edit }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /articles/1
  # DELETE /articles/1.json
  def destroy
    @article.destroy
    respond_to do |format|
      format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_article
      @article = Article.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def article_params
      params.require(:article).permit(
      :title,
      :content,
      :editer,
      categories_attributes: [:id, :name])
    end
end

viewsの設定

フォーム画面

1
2
3
4
5
6
<div class="field">
    <%= f.label :カテゴリー %>
    <%= f.fields_for :categories do |category| %>
    <%= category.text_field :name %>
    <% end  %>
  </div>

フォーム画面の全体はこうなる

 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
28
29
30
31
32
33
34
35
36
37
38
39
<%= form_for(article) do |f| %>
  <% if article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(article.errors.count, "error") %> prohibited this article from being saved:</h2>

      <ul>
      <% article.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end  %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :タイトル %>
    <%= f.text_field :title %>
  </div>

  <div class="field">
    <%= f.label :内容 %>
    <%= f.text_field :content %>
  </div>

  <div class="field">
    <%= f.label :カテゴリー %>
    <%= f.fields_for :categories do |category| %>
    <%= category.text_field :name %>
    <% end  %>
  </div>

  <div class="field">
    <%= f.label :編集者 %>
    <%= f.text_field :editer %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end  %>

Show画面

1
2
3
4
5
6
<p>
  <strong>Category:</strong>
  <% @article.categories.each do |category| %>
      <td><%= category.name %></td>
  <% end  %>
</p>

これで終わり。

See Also