I need help on figuring how to make a link for my Product that enables users to subscribe to it. I first have my Subscription model:
class Subscription < ActiveRecord::Base
attr_accessible :subscribable_id
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
end
Then my Product model:
class Product < ActiveRecord::Base
attr_accessible :name, :price
belongs_to :user
has_many :subscriptions, :as => :subscribable
end
My plan is to make my view, similar to the DELETE method a link to click to subscribe to a product. Here is my routes, controller and then view:
resources :products do
post :subscribe_product, :on => :collection
end
ProductsController:
def subscribe_product
@product = Product.find(params[:id])
# Not sure what goes here next?
# Something like: user.subscriptions.create(:subscribable => product)
end
View:
<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>
<td><%= link_to 'Subscribe', :controller => "products", :action => "subscribe_product", :id => product.id %></td>
</tr>
</tbody>
<% end %>
</table>
Right now this gives a strange error:
ActiveRecord::RecordNotFound in ProductsController#show
Couldn't find Product with id=subscribe_product
Theirs 2 things,
- Creating the method to subscribe.
- Making the link correct.
How would I do these two?
Your
subscribe_productpath uses POST, so you’ll want to change your link to use that method:Your action will probably look something like this: