2012-04-05 62 views
0

我需要幫助確定如何爲我的Product創建鏈接,以便用戶訂閱它。我第一次有我Subscription型號:創建一個訂閱產品的鏈接?

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方法的鏈接點擊訂閱產品。這裏是我的路線,控制器,然後查看:

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 

查看:

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

眼下這給出了一個奇怪的錯誤:

ActiveRecord::RecordNotFound in ProductsController#show 

Couldn't find Product with id=subscribe_product 

他們的2件事,

  1. 創建訂閱方法。
  2. 使鏈接正確。

我會怎麼做這兩個?

回答

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

默認的link_to使用GET,所以你的路由器會認爲你只是試圖去ProductsController的#秀與第一個參數是該ID

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

這是一個GET請求到產品控制器的ID PARAM subscribe_product。

如果你將:method =>:post傳遞給你的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