I have an application that allows users to like a message. When someone likes a message, the mail request works, but the view does not refresh unless I refresh the page. I am stuck on this. This is what I have so far:
Javascript
$('.favorite').on('click', function() {
var $heart = $(this).find('.fa');
$heart.removeClass('fa-heart-o').addClass('fa-heart');
$.post('/favorites', {
favorite: { post_id: $(this).attr('data-id') }
},
function(data) {
console.log(data);
});
});
Controller
def create
post = Post.find_by_id(favorite_params[:post_id])
if current_user.favorite_posts.include? post
render json: {}, status: :bad_request
else
@favorite = current_user.favorites.new(favorite_params)
if @favorite.save
render json: @favorite
else
render json: { errors: @favorite.errors.full_messages }, status: :unprocessable_entity
end
end
end
This view
<% if current_user.favorite_posts.include? post %>
<span class="fa fa-heart"> <%= post.favorites.count %></span>
<% else %>
<span class="fa fa-heart-o"> <%= post.favorites.count %></span>
<% end %>
Any help is appreciated. Thanks.
robb source
share