2012-04-05 8 views
0

私はProductのリンクを作成してユーザーが購読できるようにする方法について助けが必要です。製品を購読するためのリンクを作成していますか?

class Subscription < ActiveRecord::Base 
    attr_accessible :subscribable_id 
    belongs_to :subscriber, :class_name => "User" 
    belongs_to :subscribable, :polymorphic => true 
end 

その後、私のProductモデル::

class Product < ActiveRecord::Base 
    attr_accessible :name, :price 
    belongs_to :user 
    has_many :subscriptions, :as => :subscribable 
end 

私の計画はDELETE方法製品を購読するにはクリックしたリンクに似て、私の見解を作ることである私が最初に私のSubscriptionモデルを持っています。ここに私のルート、コントローラがあり、その後表示:

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 

ビュー:

ActiveRecord::RecordNotFound in ProductsController#show 

Couldn't find Product with id=subscribe_product 

<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> 

今、これは奇妙なエラーが発生します彼らの2つのもの、

  1. 購読する方法を作成します。
  2. リンクを正しく作成してください。

私はこれらの2をどのように行うのでしょうか?デフォルトのlink_toによって

答えて

0

あなたsubscribe_productパスはPOSTを使用していますので、あなたが変更したいと思うあなたの

:あなたの行動は、おそらくこのようになります

<%= link_to 'Subscribe', {:controller => "products", :action => "subscribe_product", :id => product.id}, :method => :post %> 

:そのメソッドを使用するためのリンク

@product.subscriptions << Subscription.new(:user_id => current_user.id) 
2

はGET使用していますので、あなたのルータは、あなたが最初のパラメータは、これがIDのparamを持つ製品のコントローラにGET要求であるID

http://yoursite.com/products/subscribe_product/5 

ことでProductsControllerの#ショーに行くことにしようとしていると考えてsubscribe_productの

あなたが渡す場合は、次の方法=>:ポストをあなたのlink_toヘルパーに、それはあなたのルータが期待しているものであるPOSTリクエストを発行します。

<%= link_to 'Subscribe', :controller => "products", :action => "subscribe_product", :id => product.id, :method => :post %> 

ユーザーモデルを掲示しないと、私は確実に知ることはできませんが、この方法は、次のようになります。

@product.subscriptions.create(:user_id => user.id) 
# user.id would be current_user.id, or whatever you are storing the current user as 
関連する問題