LoginSignup
6
7

More than 5 years have passed since last update.

[学習用]Rails5 投稿+カテゴリー+コメント機能を10分で速攻立ち上げる手順

Last updated at Posted at 2018-08-24

10minitRails5.png

忘れそうなので練習ついでに、速攻立ち上げ手順
Rails5のコマンドにも慣れたので、できるだけ短縮化しておきたい。

アプリ作成

アプリ作成

$ rails new articleapp -d postgresql
$ cd articleapp

カテゴリー作成

$ rails g scaffold Category name:string
$ rails db:migrate

投稿作成

$ rails g scaffold Article name:string title:string content:text user_id:integer category_id:integer
$ rails db:migrate

コメント作成

コメント投稿作成

$ rails g model Comment commenter:string body:text article:references
$ rails g controller Comments
$ rails db:migrate

※忘れたとき用:controller Commentsにアクション名を付け足してないのは、Viewsが要らないから。

コメント関連付け

config/routes.rb
resources :articles do
  resources :comments
end
app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :article
end
app/models/article.rb
class Article < ApplicationRecord
  has_many :comments, dependent: :delete_all
end

※dependent: :delete_all を入れないとコメントが入っている場合に削除できないエラーが出る。

コメント投稿作成

app/controllers/comments_controller.rb
class CommentsController < ApplicationController
  def create
    @article = Article.find(params[:article_id])
    # @comment = @post.comments.create(params[:comment])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
  def comment_params
    params.require(:comment).permit(:body, :commenter)
  end
end

コメントViews編集

app/views/articles/show.html.erb
<h2>コメント</h2>
<% @article.comments.each do |comment| %>
  <p>
    <%= comment.commenter %>: <%= comment.body %>
    <%= link_to '削除', [comment.article, comment],
                :confirm => 'よろしいですか?',
                :method => :delete %>

  </p>
<% end %>

<h2>コメントを書く</h2>
<%= form_for([@article, @article.comments.build]) do |f| %>
  <div class="field">
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </div>
  <div class="field">
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

カテゴリーの関連付け

カテゴリーの関連付け

app/models/category.rb
class Category < ApplicationRecord
  has_many :articles
end
app/models/article.rb
class Article < ApplicationRecord
  belongs_to :category
end

カテゴリーの表示

app/views/articles/_form.html.erb
  <div class="field">
    <%= form.label :category_id %>
    <%= form.select :category_id, Category.all.map{|o| [o.name, o.id]} %>
  </div>
app/view/shops/index.html.erb
<%= article.category.name %>
app/view/shops/show.html.erb
<%= @article.category.name %>

これで最低限の機能はそろう。
ここまでエラー無く無事立ち上がった。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7