This is blowing my mind, and there is so much going on that I just need to ask here for help.
Right now, I have a listing of resources. Inside each resource, it allows someone to ‘add it as a favorite’ by clicking a link. I have it working with normal redirection, but as for integrating ajax so they can favorite without the page refreshing, I am completely lost…
- Right now I have it as a “put” action it seems for CRUD ‘update’
FavoritesController (update is the only action in this controller)
def update
@favorite = Favorite.find_or_initialize_by_resource_id_and_user_id(params[:id], current_user.id)
if @favorite.persisted?
@favorite.destroy
else
if @favorite.valid?
@favorite.save
end
end
redirect_to root_url
end
My view:
<%= link_to "", favorites_path(:id => resource.id), :class => "star#{star_post?(resource)}", :method => "put" %>
My routes:
resource :favorites, :only => [:update]
My JS:
$('.res-list .star').click(function(){
$.put('/favorites/?id=' + $(this).attr('data-id'));
return false;
});
There’s a couple of ways to do this. You can use
link_to_functionthrough which you can pass a javascript method (you can even pass a custom one if you’ve defined it in the view or in application.js). In this method, you can set up your AJAX call to hit your update action.View (using jQuery’s
putmacro):Another way to do this is to give your link an addition HTML selector. Again, you would need to write a bit of js to hit your update action. I tend to like this way because I like to use buttons and what not instead of
<a href="#">tags. (Though honestly I ended up just creating abutton_to_functionmethod that callscontent_tag(:button)instead ofcontent_tag(:a))