I'm creating a website where users can mark and unmark items as "favorite".
I implemented this via Ajax using Rails' form attribute remote: true
so whole page does not reloaded, just status of item is changed.
I have two methods in FavouritesController
def create
Favourite.create!(item_id: params[:favourite][:item_id])
respond_to { |format| format.js }
end
def destroy
Favourite.find(params[:id]).destroy!
respond_to { |format| format.js }
end
The problem is:
I want to call another action from the same controller to "unmark" item in another view. I use code below but when I click on link - old method destroy
is called from controller, instead of desired delete_from_index_list
method.
I need two separate methods because they returns different javascript (jquery).
<%= link_to "delete", @favourite, method: :delete, remote: true, action: 'delete_from_index_list' %>
Check out the link_to documentation - I this will describe what you want.
I haven't tested this, but I'm guessing you want:
<%= link_to "delete", controller: 'favourites', action: 'delete_from_index_list', id: @favourite, remote: true %>
If it were my code, I would find the route for the delete_from_index_list
method, and call it this way:
<%= link_to "delete", route_for_delete_from_index_list_path(@favourite), method: :delete %>
This way it's more resourceful, whereas the former example is non-resourceful.