shou.com
JP / EN

Railsでブログを作る

Wed Sep 13, 2017
Wed Sep 13, 2017

やりたいこと、ブログ投稿する時にカテゴリーも一緒に作る。カテゴリーは、あらかじめ作ってあるやつを使用します。 イメージはこんな感じ。rails5を使用してます。

railsでブログを作る

ブログとカテゴリーは分けてあるので、accepts_nested_attributes_forを使ってブログを作ると同時にカテゴリーも選択できるようにします。

モデル

1
2
3
4
5
#blog.rb
class Blog < ApplicationRecord
  has_one :category, dependent: :destroy
  accepts_nested_attributes_for :category, allow_destroy: true
end

カテゴリー

1
2
3
class Category < ApplicationRecord
  belongs_to :blog, optional: true
end

コントローラー

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#BlogsController
def new
    @blog = Blog.new
    @blog.build_category
  end

  def blog_params
        params.require(:blog).permit(
        :title,
        :content,
        :editer,
        category_attributes: [:id, :name])
  end

View

親要素のブログと子要素のカテゴリーを一緒に登録します。ちなみにselectにbootstrapのクラスを適用するには<%= category.select :name, ['ガジェット', '子育て', 'エンタメ', 'IT', '海外', '生活'], { include_blank: "選択してください"}, class: "form-control" %>とします。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#_form.html.erb
<%= form_for(blog) do |f| %>
 <div class="field">
   <%= f.label :カテゴリー %>
    <%= f.fields_for :category, @blog.category do |category| %>
    <%= category.select :name, ['ガジェット', '子育て', 'エンタメ', 'IT', '海外', '生活'], { include_blank: "選択してください"}, class: "form-control" %>
   <% end  %>
  </div>


  <div class="field">
    <%= f.label :タイトル %>
    <%= f.text_field :title, class: "form-control", placeholder: "タイトル" %>
   </div>

   <div class="actions">
      <%= f.submit '作成', class: "btn btn-primary btn-lg btn-block"  %>
    </div>
 <% end  %>

テーブル

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#schema.rb
enable_extension "plpgsql"

  create_table "blogs", force: :cascade do |t|
    t.string   "title"
    t.string   "content"
    t.string   "editer"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "blog_id"
  end

実際に作成してみる。成功。

railsでブログを作る

showのview

 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
#blogs/show.html.erb
<p id="notice"><%= notice %></p>

<p>
  <strong>Title:</strong>
  <%= @blog.title %>
</p>

<p>
  <strong>Content:</strong>
  <%= @blog.content %>
</p>

<p>
  <strong>Category:</strong>
      <td><%= @blog.category.name %></td>
</p>

<p>
  <strong>Editer:</strong>
  <%= @blog.editer %>
</p>

<%= link_to 'Edit', edit_blog_path(@blog) %> |
<%= link_to 'Back', blogs_path %>

最初は、データベースから選択できるようにしようとかしていましが、カテゴリー数が少数の場合は、こんなんで問題なさそう。

Tags
See Also