0

The problem is that all the "into it" buttons on the page have the same id and all the "undo" have the same id thus clicking one offsets others. Also the buttons only toggle once. I'm very new to rails,CSS,ajax and I appreciate the help, thank you. enter image description here

Micropost_Helper.rb

def toggle_like_button(micropost, user)
  if user.voted_for?(micropost)
    link_to "undo", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"unvote_form", :remote => true
  else
    link_to "Into it!", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"vote_form", :remote => true
  end
end

Micropost Controller

def like
  @micropost = Micropost.find(params[:id])
  if @micropost.user_id != @current_user
    if @current_user.voted_for?(@micropost)
      @current_user.unvote_for(@micropost)
      respond_to do |format|
        format.html { redirect_to :back }
        format.js
      end
    else
      @current_user.vote_for(@micropost)
      respond_to do |format|
        format.html { redirect_to :back }
        format.js
      end
    end
  end
end

VIEW/microposts/like.js.erb <-- with this i can only click the button's once, need help here as well

$("#vote_form").html("undo")
$("#unvote_form").html("Into it!")
4

1 回答 1

3

您应该像这样将 uniq id 附加到每个按钮:

def toggle_like_button(micropost, user)
  if user.voted_for?(micropost)
    link_to "undo", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"unvote_form_#{micropost.id}", :remote => true
  else
    link_to "Into it!", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"vote_form_#{micropost.id}", :remote => true
  end
end

然后您可以在 like.js.erb 中引用一个按钮:

$("#vote_form_<%=@micropost.id%>").html("undo")
$("#unvote_form_<%= @micropost.id%>").html("Into it!")

这样您将拥有有效的 html,并且您的问题应该得到解决。

于 2013-01-04T09:29:30.000 回答