【发布时间】:2018-06-16 23:07:14
【问题描述】:
我有 Comment belongs_to Post 和 Post has_many Comments,评论模式如下:
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :text, presence: true
end
添加新cmets的表单位于Posts显示视图,如下:
<%= form_with(model: [ @post, @post.comments.build ], local: true) do |form| %>
<% if @comment.errors.any?%>
<div id="error_explanation">
<ul>
<% @comment.errors.messages.values.each do |msg| %>
<%msg.each do |m| %>
<li><%= m %></li>
<%end %>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= form.text_area :text , {placeholder: true}%>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
评论创建动作,如下:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = Comment.new(comment_params)
@comment.post_id = params[:post_id]
@comment.user_id = current_user.id
if @comment.save
redirect_to post_path(@post)
else
render 'posts/show'
end
end
private
def comment_params
params.require(:comment).permit(:text)
end
end
我需要渲染帖子/显示页面以显示 Comment 验证错误,但问题是我在 CommentsController 控制器中而不是 PostsController 所以页面中使用的所有对象/show 视图将为空。
如何将@comment 对象传递给页面/显示? 我想过使用 flash 数组,但我正在寻找更传统的方式。
【问题讨论】:
标签: ruby-on-rails