当我尝试通过点击链接订阅产品时:
<%= 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呢?
答案 0 :(得分: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)
答案 1 :(得分:1)
请试试这个。将您的路线更改为:
resources :products do
post :subscribe
end
然后更改您的链接:
<%= link_to "Subscribe", subscribe_products_path(:id => product.id), :method => :post %>
答案 2 :(得分: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