Search code examples
ruby-on-railscontrollermodels

Pass a variable from controller to view


I do a simple blog on rails. I have a Post model and a Comment model. When you create a comment, if comment is not valid, i want to show the error. How do I do?

model Post:

#/models/post.rb 
class Post < ActiveRecord::Base
   has_many :comments
   validates :title, :content, :presence => true
end

model Comment:

#/models/comment.rb
class Comment < ActiveRecord::Base
   belongs_to :post
   validates :name, :comment, :presence => true
end

Comments Controller

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end

View for comment form:

/views/comments/_form.html.erb

<%= form_for([@post, @post.comments.build]) do |f| %>
  <% if @comment.errors.any?  %>
     error! 
  <% end %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :comment %><br />
    <%= f.text_area :comment %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

/views/posts/show.html.erb

<%= render 'comments/form' %>

How to pass @comment from the controller CommentController to view /post/show.html.erb ?

Thanks in advance.


Solution

  • Put render "posts/show" instead of redirect_to post_path(@post) in your CommentsController.