1

I've a simple application that contains post that has many comments.

I can create comments from posts#show with the following form.

<%= form_for @comment, :remote => true, :html => {:'data-type' => 'html', :id =>                 'create_comment_form' }, :'data-update-target' => 'comments-container'$
    <%= f.text_area :content %>
    <%= f.hidden_field :post_id, :value => @post.id %>
    <%= f.submit 'Submit', :disable_with => 'Please wait...', :class => 'submit' %>
<% end %>

And then I show the comments with

<div id="comments-container">
  <%= render "posts/comments"  %>
</div>

which loops through @post.comments.

Is it possible to update @post.comments and rerender the partial when the form is submited?

2 Answers 2

4

Do you currently render anything from your posts#create action? Either way, you'll want to render a create.js.erb (create this file in app/views/posts/) like @jvnill says:

def create
  # do your thang..
  respond_to do |format|
    format.js do
      # any stuff you want to do when responding to JS
    end
  end
end

This will automatically render create.js.erb, which should be something like:

$('#comments-container').html('<%= escape_javascript(render "posts/comments") %>');

Edit - you're getting the problem you describe with render because your trying to render from an asset. Put it in your views directory.

Sign up to request clarification or add additional context in comments.

Comments

2

It is possible to do that. In create.js.erb, try

$('#comments-container').html('#{escape_javascript render('posts/comments')}')

Make sure that whatever instance variables you're using inside the partial is declared.

UPDATE: A better way would be to just append the comment at the end of the div.

3 Comments

$("#comments-container").html("<%= escape_javascript( render(:partial => "posts/comments") ) %>"); results in undefined method `render' for #<#<Class:0x00000002100ae8>:0x00000003515dd0>
I guess I will return the comments as json and append it, the downside of this is that you lose the benefit of using a partial for formating the comments
no you can still use a partial for the comments. inside posts/comments, use a partial to render each comment, then use that partial to append to the div. as for your error, it is weird you're getting that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.