当我的模型是:
时,我无法弄清楚如何删除我对产品的订阅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 &amp;的页/ 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>
答案 0 :(得分:1)
看起来链接中的订阅应该是@subscription
,表示您在控制器中声明它。否则,我需要查看整个页面代码以及呈现它的操作
更新: 所以你没有定义订阅。试试这个:
<td><%= link_to "Unsubscribe", { :controller => "products", :action => "unsubscribe_product", :id => product.id }, :method => :delete %></td>
然后按如下方式修改您的操作:
def unsubscribe_product
product = Product.find(params[:id])
@subscription = product.subscriptions.find_by_subscriber_id(current_user.id)
if @subscription.destroy
redirect_to :back
else
redirect_to :back
end
end