前提・実現したい
taskのshowで詳細情報を表示しそれに対しての返信コメントを返せるようにしたいのです
発生している問題・エラーメッセージ
返信コメント入力欄に書き込み投稿ボタンを押すと
メッセージの投稿に失敗しました。と出てsave出来ずに帰ってきます。
試したこと
taskのshowページのform_with周りや
Controllerのcreate、reply_paramsなどの打ち間違いチェックはしました。
Rails
1<div class="container"> 2 <div class="row"> 3 <div class="offset-md-3 col-md-6 offset-md-3"> 4 <table class="table table-striped"> 5 <tr> 6 <th>タイトル</th> 7 <td><%= @task.title %></td> 8 </tr> 9 <tr> 10 <th>送信者</th> 11 <td><%= @task.user.name %></td> 12 </tr> 13 <tr> 14 <th>期日</th> 15 <td><%= @task.deadline %></td> 16 </tr> 17 </table> 18 <div class="card"> 19 <div class="card-header"> 20 コメント 21 </div> 22 <div class="card-body"> 23 <%= @task.comment %> 24 </div> 25 </div> 26 27 <%= form_with(model: @reply, local: true) do |f| %> 28 <%= f.label :comment, '返信コメント入力' %> 29 <%= f.text_field :comment %> 30 31 <%= f.submit '投稿' %> 32 <% end %> 33 </div> 34 </div> 35</div>
Rails
1class TasksController < ApplicationController 2 def show 3 @task = Task.find(params[:id]) 4 @reply = Reply.new 5 6 end 7 8 def new 9 @task = current_user.tasks.build 10 end 11 12 def create 13 @task = current_user.tasks.build(task_params) 14 if @task.save 15 flash[:success] = 'メッセージを投稿しました。' 16 redirect_to root_url 17 else 18 @tasks = current_user.tasks.order(id: :desc).page(params[:page]) 19 flash.now[:danger] = 'メッセージの投稿に失敗しました。' 20 render 'toppages/index' 21 end 22 end 23 24 def destroy 25 end 26 27 private 28 29 def task_params 30 params.require(:task).permit(:title, :staff, :deadline, :comment) 31 end 32end 33
Rails
1class RepliesController < ApplicationController 2 3 def index 4 @reply = Replies.all 5 end 6 7 def create 8 @reply = Reply.new(reply_params) 9 if @reply.save 10 flash[:success] = 'メッセージを投稿しました。' 11 redirect_to @replies 12 else 13 @tasks = Task.where(staff: current_user.name) 14 flash.now[:danger] = 'メッセージの投稿に失敗しました。' 15 render 'toppages/index' 16 end 17 end 18 19 private 20 21 def reply_params 22 params.require(:reply).permit(:comment) 23 end 24end 25
補足情報(FW/ツールのバージョンなど)
バリデーションの書き方も合っているのか不安になったので載せておきます。
Rails
1class User < ApplicationRecord 2 before_save { self.email.downcase! } 3 validates :name, presence: true, length: { maximum: 50 } 4 validates :email, presence: true, length: { maximum: 255 }, 5 format: { with: /\A[\w+\-.]+@[a-z\d\-.]+.[a-z]+\z/i }, 6 uniqueness: { case_sensitive: false } 7 has_secure_password 8 9 has_many :tasks 10 has_many :replies 11end
Rails
1class Task < ApplicationRecord 2 belongs_to :user 3 has_many :replies 4end
Rails
1class Reply < ApplicationRecord 2 belongs_to :title, class_name: 'Task' 3 belongs_to :user 4end
class Reply のDBです
Rails
1class CreateReplies < ActiveRecord::Migration[5.2] 2 def change 3 create_table :replies do |t| 4 t.references :title, foreign_key: { to_table: :tasks } 5 t.references :user, foreign_key: true 6 t.string :comment 7 8 t.timestamps 9 end 10 end 11end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。