I am trying to update a rails partial while using Ajax and having some trouble. Basically I have a Post with a Karma attribute. Users can vote up and vote down to take and remove Karma from the post. I would like to allow the user to asynchronously update the post value using Ajax and im running into a NilClass error that im hoping you can help me with. The error im getting is undefined method `karma' for nil:NilClass (in my _karma_value.erb file), and my files look like below. Im totally stuck!
posts_controller.rb
def add_karma
# Save the page that the request came from
session[:initial_page] ||= request.referer
@post = Post.find(params[:id])
@post.karma = @post.karma + 1
@post.update_attributes(params[:post])
respond_to do |format|
format.html { redirect_to session[:initial_page] } #redirect back to requesting page
format.json { head :no_content }
format.js {}
end
end
add_karma.js.erb
$('#add_karma').html(
"<%= escape_javascript(render('_karma_value', post: @post)) %>");
index.html.erb
...
<b>Karma:</b>
<%= render(:partial => 'karma_value', :locals => {:post => @post}) %> <br>
...
_karma_value.erb
<% if !(post.karma.nil?) %>
<%= post.karma %>
<% end %>
Yes, @post will be nil in the partial.
Because, while rendering partial, you have mentioned the local variable post as @post. But using @post in partial.
Just use post in that partial.
in _karma_value.html.erb
<% if !(post.karma.nil?) %>
<%= post.karma %>
<% end %>