1

I'm trying to implement an action which will be invoked when user submits a new comment via ajax. When the comment is saved single comment partial must return. But it seems that render doesn't work as expected from ApplicationController. It displays an error that the view is not found, but it is in place (100%). When I'm adding :partial parameter it works, but doesn't pass any variables (and I need them!). Here's the controller code:

class ApplicationController < ActionController::Base
 protect_from_forgery
 def comment
 comment = Comment.new({
 story_id: params[:story_id],
 content: params[:content]
 })
 if comment.save
 render 'shared/comments/comment', comment: comment
 else
 render nothing: true, status: 400
 end
 end
end
Mischa
43.4k9 gold badges101 silver badges111 bronze badges
asked Mar 30, 2013 at 14:00
5
  • 2
    I'm wondering why aren't you using a CommentsController? Commented Mar 30, 2013 at 14:06
  • Since this action will be used by several other controllers, it make sense for me to define it in global controller. And I think it's overkill to use separate controller for one action. Commented Mar 30, 2013 at 14:09
  • 1
    I have to disagree with you, since this action handles the resource Comment it should be placed in the CommentsController, even if you have a comment form in a non CommentsController view. Also, there is no problem to create a controller for just one action. Commented Mar 30, 2013 at 14:15
  • 1
    I have to agree with @nicolasiensen. Your action looks like a good candidate for a create action inside a CommentsController, in keeping with REST practices. Commented Mar 30, 2013 at 14:22
  • Okay, thanks, I'll think about that. Commented Mar 30, 2013 at 14:24

1 Answer 1

2

Try using this syntax:

render :partial => 'shared/comments/comment', :locals => { :comment => comment }
answered Mar 30, 2013 at 14:05
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Yeah, this works, but I've read in documentation that in new versions of Rails, you can just pass your variables without locals array and it works for me in other places, but not here. Why?
@DimaKnivets, according to Rails Guides, you should use object: comment in that case, not comment: comment.
Yes, in this case since the variable has the same name as the partial, you can use object: comment. But I don't see any mention of this being a preferred option in the docs.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.