Question

I have two models, users and materials. Users can favourite materials. I have set up the relationships and the code for favouriting works fine but I can't seem to get the code for unfavouriting right. I have the following code for unfavouriting:

Materials Controller (in show action where unfavourite form is)

@favourite = Favmat.where(:user_id => current_user.id, :material_id => @material.id)

Note: I use this code to decide which button to show in the view. Assuming a record exists we get this:

View

<%= form_for @favourite, :method => :delete do |f| %>
<%= f.submit "Unfavourite" %>
<% end %>

The problem seems to be here. Nothing I do seems to get me a working route to the destroy action in the favmats controller. I have tried using a form_tag instead but then I get very odd routes that don't work.

Favmats Controller

def destroy
  Favmat.find(params[:id]).destroy
  respond_to do |format|
    format.html { redirect_to @material }
    format.js
  end
end

Update

I have also tried using link_to instead of a form. The code is as follows:

<%= link_to "Unfavourite", favmat_path, method: "delete" %>

The weird thing is that the html for this takes the favmat id from the material, not the favmat object. I don't know how to get the favmat object id in there. Nothing seems to work.

Was it helpful?

Solution

Try passing @favourite object instead of favmat_path to link_to:

<%= link_to "Unfavourite", @favourite, method: :delete %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top