创建订阅产品的链接?

时间:2012-04-05 20:38:54

标签: ruby-on-rails ruby ruby-on-rails-3

我需要帮助来确定如何为我的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

他们的两件事,

  1. 创建订阅方法。
  2. 使链接正确。
  3. 我怎么做这两个?

2 个答案:

答案 0 :(得分:2)

默认情况下,link_to使用GET,因此您的路由器认为您正在尝试使用第一个参数作为ID

转到ProductsController #show
http://yoursite.com/products/subscribe_product/5

这是对产品控制器的get请求,其id参数为subscribe_product。

如果您通过:method =&gt; :发布到你的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

答案 1 :(得分: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)