I want Follow button that changes to Un-Follow when its clicked. But when it submits form, it doesn't do any at all. Why?
My codes are like these
-----Action(users_controller.rb)-----
def set_follow
friend = User.find_by_username(params[:username])
if f = Friendship.find(:first, :conditions => { :user_id => current_user.id, :friend_id => friend.id})
f.destroy
flash[:notice] = "Now added to follow list"
respond_to do |format|
format.html { redirect_to set_follow }
format.js
end
#redirect_to :back
else
Friendship.create(:user_id => current_user.id, :friend_id => friend.id)
flash[:error] = "Now deleted from follow list"
respond_to do |format|
format.html { redirect_to set_follow }
format.js
end
#redirect_to :back
end
end
-----Form(users/index.html.erb)-----
<div id="follow_status">
<% if user_signed_in? && current_user.friends.find_by_id(user.id) %>
<%= link_to sanitize('<i class="icon-remove icon-white"></i> ') + 'Un-Follow', follow_user_path(user.username), :class => 'btn', remote: true %>
<% elsif current_user != user %>
<%= link_to sanitize('<i class="icon-ok icon-white"></i> ') + 'Follow', follow_user_path(user.username), :class => 'btn btn-primary', remote: true %>
<% end %>
</div>
-----JS View(set_follow.js.erb)-----
$("#follow_status").html("<%= escape_javascript(render f) %>");
Bit of a different method but I would just do this with JQuery
$('.btn').click( function() {
if( $('.btn').html() == 'Follow') {
$('.btn').html('Unfollow');
}
else if( $('.btn').html() == 'Unfollow') {
$('.btn').html('Follow');
}
});
This is just a bit of an example how you could do it. You would probably want to use a more specific chain of classes in the jquery
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.