Reputation: 27192
I'm having trouble figuring out how to delete my subscription for a product when my models are:
class User
has_many :products
has_many :subscriptions, :foreign_key => :subscriber_id
end
class Product
has_many :subscriptions, :as => :subscribable
end
class Subscription
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
end
And I try to delete by my view and controller setup:
def unsubscribe_product
@subscription = Subscription.find(params[:id])
if @subscription.destroy
redirect_to :back
else
redirect_to :back
end
end
<td><%= link_to "Unsubscribe", { :controller => "products",
:action => "unsubscribe_product",
:id => subscription.id },
:method => :delete %></td>
But get the error:
NameError in Pages#subscribe_area
undefined local variable or method `subscription' for #<#<Class>
I don't understand why it doesn't work this way. I have an instance to find the subscription. Why can't I use it? Will this automatically map to the current users subscriptions too?
Thanks, could use the help.
Edit
PagesController & pages/subscribe_area.html.erb
def subscribe_area
@products = current_user.products
end
<table>
<% for product in @products %>
<tbody>
<tr>
<td><%= product.name %></td>
<td><%= product.price %></td>
<td><%= link_to 'Delete', product, :confirm => 'Are you sure?', :method => :delete %></td>
<% if current_user.subscribed_for?(product) %>
<td><%= link_to "Unsubscribe", { :controller => "products", :action => "unsubscribe_product", :id => subscription.id }, :method => :delete %></td>
<% else %>
<td><%= link_to "Subscribe", { :controller => "products", :action => "subscribe_product", :id => product.id }, :method => :post %></td>
<% end %>
</tr>
</tbody>
<% end %>
</table>
Upvotes: 1
Views: 843
Reputation: 1484
It looks as though subscription in the link should be @subscription
saying you are declaring it in your controller. Else I would need to see the whole page code as well as the action that renders it
Updated: So you are not defining subscription. Try this instead:
<td><%= link_to "Unsubscribe", { :controller => "products", :action => "unsubscribe_product", :id => product.id }, :method => :delete %></td>
Then modify your action as follows:
def unsubscribe_product
product = Product.find(params[:id])
@subscription = product.subscriptions.find_by_subscriber_id(current_user.id)
if @subscription.destroy
redirect_to :back
else
redirect_to :back
end
end
Upvotes: 1