1

当我的模型为:

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>
4

1 回答 1

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
于 2012-04-07T23:06:57.867 回答