2015-11-02 49 views
0

我有一個產品模型,一個用戶模型和一個描述模型。產品有用戶通過訂閱,用戶有很多產品通過訂閱,訂閱屬於兩者。如何銷燬我的訂閱?

當用戶喜歡某個產品時,它會爲此創建一個新訂閱。在我的subscription_controller中,我爲此創建了函數like_project;奇蹟般有效!

但我也嘗試創建一個unlike-project函數銷燬該特定訂閱。我只是無法讓它工作。我已經被告知要銷燬關係而不是對象,但我已經認爲訂閱就是那種關係。

那麼,我應該如何編寫我的代碼,以確保用戶也可以不像它喜歡的產品(或銷燬訂閱)?

這裏是我的我的訂閱式控制器的功能:

class SubscriptionController < ApplicationController 

before_action :authenticate_user! 
    def like_product 
    product = Product.find(params[:product_id]) 
    current_user.subscriptions.create(product: product) 

    recommender = ProductRecommender.new 
    recommender.add_to_matrix!(:users, "user-#{current_user.id}", "product-#{product.id}") 

    redirect_to product  
end 

def unlike_product 
    @subscription = Subscription.find(params[:id]) 
    product = @subscription.product 
    @subscription.destroy 

    recommender = ProductRecommender.new 
    recommender.delete_from_matrix!(:users, "product-#{product.id}") 

    redirect_to product  
end 

private 
    def subscription_params 
     params.require(:subscription).permit(:product_id, :user_id) 
    end 
end 

這是我怎麼樣一個產品:

   <div class="card-action center"> 

       <% if user_signed_in? %> 
        <%= form_tag productsubscribe_path do %> 
         <%= hidden_field_tag 'product_id', @product.id %> 
         <button type="submit" class="btn waves-effect waves-light black darken-2">Like project</button> 
        <% end %> 
       <% else %> 
        <%= link_to new_user_session_path do %> 
         <button type="submit" class="btn waves-effect waves-light black darken-2">Like project</button> 
        <% end %> 
       <% end %> 
       </div> 

...這就是我正在嘗試一個不同產品:

   <div class=""> 
       <%= form_tag productunsubscribe_path do %> 
        <%= hidden_field_tag 'product_id', @product.id %> 
         <button type="submit" class="btn waves-effect waves-light black darken-2">Unlike product</button> 
       <% end %> 
       </div> 

您可以看到的推薦程序代碼是一個推薦引擎,它將一組程序添加到Redis matri x當一個產品被喜歡時,並且當它被取消時被刪除。它不會導致任何問題,當喜歡一個產品,我假設它不喜歡一個以及;)

任何人都可以幫我嗎?

回答

0

您的unlike_product控制器方法預計使用params[:id]來查找相關訂閱。然而,在你的形式,它看起來並不像你在所有的id PARAM傳遞 - 你擁有的唯一領域是product_id

<%= hidden_field_tag 'product_id', @product.id %> 

是什麼params[:id]包含哪些內容?它是空的嗎? params[:product_id]怎麼樣?我們希望這不是空的。因此,而不是:

@subscription = Subscription.find(params[:id]) 

你,而不是尋找其中的product_id您的PARAM匹配的訂閱,以及USER_ID匹配的登錄用戶。

+0

謝謝@joshua。我認爲我明白你的意思,但我無法將它變成可行的代碼。這是我的第一次破壞,我開始覺得很愚蠢;) 我只是嘗試以下,但它不起作用: \t \t'@subscription = Subscription.where(「product_id =:id和user_id =#{current_user.id}「)' –

+0

嘗試'@subscription = Subscription.where(」product_id =#{params [:product_id]} AND user_id =#{current_user.id}「)' –

+0

或者更好的是,使用佔位符: 'Subscription.where(「product_id =?AND user_id =?」,params [:product_id],current_user.id)' –