コメント機能4
やった事
- polymorphic_pathを調べた
- 日報、コメントの新規作成に失敗した時のコードを書いた
polymorphic_path
【Rails】link_toのxxx_pathが長い時はpolymorphic_pathを使うと綺麗に書けるお話 - Qiita
を参考にパスを書き換えた。(書き方が違うだけで同じパス)
<%= form_with(scope: :comment, url: report_comments_path(@report), local: true) do |f| %>
<%= form_with(scope: :comment, url: polymorphic_path([@report, @report.comme nts.build]), local: true) do |f| %>
createに失敗した場合の処理
app/controllers/reports/comments_controller.rb
def create
report = Report.find(params[:report_id])
comment = report.comments.build(comment_params)
comment.user = current_user
if comment.save
redirect_to report_path(report), notice: t('controllers.common.notice_create', name: Comment.model_name.human)
else
redirect_to report_path(report)
end
end
この場合ヴァリデーションに引っかかり飛ばされるのは日報詳細ページだが、エラーメッセージが表示されない。
def create
@report = Report.find(params[:report_id])
@comment = @report.comments.build(comment_params)
@comment.user = current_user
if @comment.save
redirect_to report_path(@report), notice: t('controllers.common.notice_create', name: Comment.model_name.human)
else
@comments = @report.comments.order(created_at: :desc)
render 'reports/show'
end
end
こうするとエラーメッセージは表示されるが、URLがreports/id/comments
とpostで飛ばされた時のままになってしまう。
日報の詳細ページだから、reports/id
のURLにしたいが、これはrenderを使っているからしょうがないのでしょうか?
挙動に問題がなければそれでいいのか、何か修正した方が良いのか..