個人アプリ開発 コメント機能作成
コメント機能を作成しました。
1.モデル作成
[terminal] $ rails g model comment
2.モデル編集
[comment.rb] belongs_to :group belongs_to :user validates :title, presence: true validates :text, presence: true [group.rb user.rb] ーーー追記ーーー has_many :comments
3.migrationファイル編集
class CreateComments < ActiveRecord::Migration[5.0] def change create_table :comments do |t| t.references :group, foreign_key: true t.references :user, foreign_key: true t.string :title, null: false t.text :text, null: false t.date :visit_date, null: false t.timestamps end end end
[terminal] $ rails db:migrate
4.ルーティング設定
resources :groups do resources :comments, only: :create end
5.controller作成
$ rails g controller comments
6.controller編集
[comments_controller] def create @comment = Comment.create(comment_params) if @comment.save redirect_to group_path(@comment.group.id) end end private def comment_params params.require(:comment).permit(:title, :text, :visit_date).merge(user_id: current_user.id, group_id: params[:group_id]) end
一旦保存できた場合のみ記述
7.view編集
[groups_show.html.haml] - if current_user .aquarium-comments__form %h3 口コミの投稿 .form = form_for [@group, @comment] do |f| = f.text_field :title, class: 'form__title', placeholder: 'タイトルを入れてください' = f.text_area :text, class: 'form__text', placeholder: '口コミ本文を入れてください' = f.date_field :visit_date, class: 'form__date' = f.submit '投稿', class: 'form__submit'
if corrent_user でログイン時のみフォームを表示
明日以降、編集・削除機能と
保存できなかった場合の処理を作成していきます。