Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
Mike Avatar asked Jan 15 '12 13:01

Mike


2 Answers

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

like image 102
shime Avatar answered Oct 21 '22 06:10

shime


And/Or take a look at Ryan Bates Screencasts about nested models and resources:

  • http://railscasts.com/episodes/196-nested-model-form-part-1
  • http://railscasts.com/episodes/197-nested-model-form-part-2
  • http://railscasts.com/episodes/139-nested-resources

They're Rails 2 but to get an idea how it works it's ok.

Maybe also interesting for you:

  • http://railscasts.com/episodes/73-complex-forms-part-1
  • http://railscasts.com/episodes/74-complex-forms-part-2
  • http://railscasts.com/episodes/75-complex-forms-part-3
like image 28
Vapire Avatar answered Oct 21 '22 05:10

Vapire