Вопрос

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 %>

Другие советы

you pass :locals => {:post => @post} so you should use post instead of @post inside _karma_value.erb partial

Why don't you use the same exact render :partial => command in both add_karma.js.erb and index.html.erb? It seems that you are not rendering correctly the partial in the add_karma.js.erb.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top