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,
How would I do these two?
Your subscribe_product
path uses POST, so you'll want to change your link to use that method:
<%= link_to 'Subscribe', {:controller => "products", :action => "subscribe_product", :id => product.id}, :method => :post %>
Your action will probably look something like this:
@product.subscriptions << Subscription.new(:user_id => current_user.id)
By default link_to uses GET, so your router thinks you are trying to go to ProductsController#show with the first param being the ID
http://yoursite.com/products/subscribe_product/5
This is a get request to the products controller with an id param of subscribe_product.
If you pass :method => :post to your link_to helper, it will issue a post request, which is what your router is expecting.
<%= link_to 'Subscribe', :controller => "products", :action => "subscribe_product", :id => product.id, :method => :post %>
Without posting your user model, I can't know for sure, but the method will look like this:
@product.subscriptions.create(:user_id => user.id)
# user.id would be current_user.id, or whatever you are storing the current user as