0

当我尝试通过单击链接订阅产品时:

<%= 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 呢?

4

3 回答 3

2

尝试 :

resources :products do
  post :subscribe_product, :on => :member
end

它将生成如下路线:

subscribe_product_product POST     /product/:id/subscribe_product(.:format)   {:action=>"subscribe_product", :controller=>"products"}

并使用视图中的路径:

subscribe_products_path(product.id)
于 2012-04-06T09:02:10.350 回答
1

请试试这个。将您的路线更改为:

resources :products do
  post :subscribe
end

然后更改您的链接,例如:

<%= link_to "Subscribe", subscribe_products_path(:id => product.id), :method => :post %>
于 2012-04-06T03:41:14.427 回答
1

由于您要通过id,因此subscribe_product路线应该是member路线。试试这个,让我知道你得到了什么:

resources :products do
  member do
    post 'subscribe_product'
  end
end

在控制器中(绕过不可分配的属性):

def subscribe_product
  @product = Product.find(params[:id])
  subscription = Subscription.new
  subscription.subscriber_id = current_user.id
  @product.subscriptions << subscription
end
于 2012-04-06T08:06:46.620 回答