当我尝试通过单击链接订阅产品时:
<%= link_to "Subscribe", :controller => "products", :action => "subscribe_product", :id => product.id, :method => :post %>
我收到此错误并注意到参数错误。
ActiveRecord::RecordNotFound in ProductsController#show
Couldn't find Product with id=subscribe_product
{"id"=>"subscribe_product", "method"=>"post"}
我的 ProductsController 中的 subscribe_product 方法是:
def subscribe_product
@product = Product.find(params[:id])
@product.subscriptions.create(:subscriber_id => current_user.id)
end
我的路线:
resources :products do
post :subscribe_product, :on => :collection
end
这些是关联:
class User
has_many :products
has_many :subscriptions, :foreign_key => :subscriber_id
class Product
belongs_to :user
has_many :subscriptions, :as => :subscribable
class Subscriptions
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
用户订阅另一个控制器:
PagesController
def index
@product_history = current_user.products
end
end
pages/index.html.erb
<% for product in @product_history %>
<%= product.name %>
<%= product.price %>
<%= link_to "Subscribe", :controller => "products", :action => "subscribe_product", :id => product.id, :method => :post %>
<% end %>
那么为什么我的操作方法被视为 ID 呢?