當我嘗試通過點擊鏈接來訂閱產品:操作方法是:id與link_to?
<%= 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呢?
使用我的第一個link_to:'<%= link_to「Subscribe」,:controller =>「products」,:action =>「subscribe_product」,:id => product。id,:method =>:post%>',它給出了錯誤 - '沒有路由匹配[GET]「/ products/5/subscribe_product」' – LearningRoR 2012-04-06 12:50:39
我認爲你的鏈接需要看起來像這樣):'<%= link_to「訂閱」,{:controller =>「products」,:action =>「subscribe_product」,:id => product.id},:method =>:post%>'。如果這不起作用,你可以運行'rake routes | grep subscribe_product'並讓我知道你得到了什麼。 – tsherif 2012-04-06 13:01:50
我認爲它的工作,但我注意到我有'不能mass-assign受保護的屬性:subscriber_id,subscribable_type',所以我不能確定它。我不希望這些作爲大規模轉讓。現在我得到'Template Missing',但我可以有效地重定向。 – LearningRoR 2012-04-06 14:55:50