2012-04-07 6 views
1

私は私のモデルである場合、製品のための私のサブスクリプションを削除する方法を考え出すのトラブルを抱えている:Link_toは多型関連を削除しますか?

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リンク内のサブスクリプションが@subscriptionはあなたにそれを宣言していると言っべきであるかのように見えます& ページ/ 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> 

答えて

1

コントローラ。それ以外の場合は、ページコード全体とレンダリングするアクションを参照する必要があります

更新: サブスクリプションを定義していません。代わりにこれを試してみてください:

<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 
+0

はあなたMiller氏に感謝します。 – LearningRoR

関連する問題