如何销毁我的订阅?

How to destroy my subscriptions?

我有一个产品模型、一个用户模型和一个订阅模型。一个产品通过订阅获得用户,一个用户通过订阅获得多个产品,一个订阅属于两者。

当用户喜欢某个产品时,它会为此创建一个新订阅。在我的 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 矩阵,当产品不喜欢时将其删除。喜欢一个产品不会造成任何问题,我假设它也不会因为不喜欢一个产品而造成问题;)

谁能帮帮我?

您的 unlike_product 控制器方法期望使用 params[:id] 来查找相关订阅。但是,在您的表单中,您似乎根本没有传入 id 参数 - 您拥有的唯一字段是 product_id:

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

params[:id]包含什么?它是空的吗? params[:product_id] 怎么样?我们希望它不是空的。所以而不是:

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

您将寻找 product_id 与您的参数匹配且 user_id 与登录用户匹配的订阅。