当我的模型为:
class User
has_many :products
has_many :subscriptions, :foreign_key => :subscriber_id
end
class Product
has_many :subscriptions, :as => :subscribable
end
class Subscription
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
end
我尝试通过我的视图和控制器设置删除:
def unsubscribe_product
@subscription = Subscription.find(params[:id])
if @subscription.destroy
redirect_to :back
else
redirect_to :back
end
end
<td><%= link_to "Unsubscribe", { :controller => "products",
:action => "unsubscribe_product",
:id => subscription.id },
:method => :delete %></td>
但得到错误:
NameError in Pages#subscribe_area
undefined local variable or method `subscription' for #<#<Class>
我不明白为什么它不能这样工作。我有一个实例来查找订阅。为什么我不能使用它?这也会自动映射到当前用户的订阅吗?
谢谢,可以使用帮助。
编辑
PagesController & pages/subscribe_area.html.erb
def subscribe_area
@products = current_user.products
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>
<% if current_user.subscribed_for?(product) %>
<td><%= link_to "Unsubscribe", { :controller => "products", :action => "unsubscribe_product", :id => subscription.id }, :method => :delete %></td>
<% else %>
<td><%= link_to "Subscribe", { :controller => "products", :action => "subscribe_product", :id => product.id }, :method => :post %></td>
<% end %>
</tr>
</tbody>
<% end %>
</table>