I have Comment belongs_to Post and Post has_many Comments, the comment model as following:
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :text, presence: true
end
The form which adds new comments is located in Posts show view, as following:
<%= 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 %>
The Comments create action, as following:
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
I need to render the posts/show page to show Comment validation errors, but the problem is I'm in CommentsController controller not PostsController so all objects used in pages/show view will be null.
How can I pass the @comment object to pages/show? I thought about using flash array, but I'm looking for more conventional way.