ActiveRecord 删除所有记录而不是一个记录

ActiveRecord deleting all records instead of one

我正在尝试删除用户订阅,但每当我点击“赞”时,current_user 的所有订阅都会被删除,而不仅仅是目标订阅。唯一似乎有效的是原始 sql

执行sql

conn = ActiveRecord::Base.connection
    conn.execute(%Q{
        delete from user_subscriptions
        where user_id = #{user_id}
        and app_id = #{app_id}
})

app/controllers/user_subscriptions_controller.rb

class UserSubscriptionsController < ApplicationController
  ...

  def destroy
    user_id = params[:user_id]
    app_id = params[:app_id]
    UserSubscription.find_by(user_id: user_id, app_id: app_id).destroy
    flash[:notice] = 'You will no longer receive notifications of new builds.'
    redirect_to root_path
  end
end

app/views/apps/_full.html.erb

...
<h5 class='caption-text cols-lg-12'>
  <% if @subs.include? app.id %>
    <%= link_to 'stop notifications', destroy_subscription_path(session[:user_id], app.id) %>
  <% else %>
    <%= link_to 'recieve notifications', create_subscription_path(session[:user_id], app.id) %>
  <% end %>
</h5>

db/migrate

class CreateUserSubscriptions < ActiveRecord::Migration
  def change
    create_join_table :users, :apps, table_name: 'user_subscriptions'
    execute 'ALTER TABLE user_subscriptions ADD PRIMARY KEY (user_id, app_id);'
  end
end

config/routes.rb

get 'user_subcriptions/create/:user_id/:app_id', to: 'user_subscriptions#create', as: 'create_subscription'
get 'user_subcriptions/destroy/:user_id/:app_id', to: 'user_subscriptions#destroy', as: 'destroy_subscription'

app/models/user_subscription.rb

class UserSubscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :app
end

app/models/app.rb

class App < ActiveRecord::Base
  has_many :versions
  has_many :user_subscriptions
  has_many :users, through: :user_subscriptions
  validates :name, uniqueness: { case_sensitive: false, scope: :app_type }

app/models.user.rb

class User < ActiveRecord::Base
  has_many :user_subscriptions
  has_many :apps, through: :user_subscriptions

app/controllers/apps_controller.rb

class AppsController < ApplicationController
  def index
    redirect_to root_path unless user_signed_in?
    apps = App.order(name: :asc).all
    @subs = @current_user.user_subscriptions.map(&:app_id) || []
    @android_apps = apps.select { |a| a.app_type == 'android' } unless iphone? || ipad?
    if iphone? || ipad?
      @ios_apps = apps.includes(:versions).select do |app|
        app.iphone? == iphone? && app.ipad? == ipad?
      end
    elsif android? == false
      @ios_apps = apps.includes(:versions).select do |app|
        app.ipad? || app.iphone?
      end
    end
  end
end

您需要使用 DELETE 动词而不是 GET:

routes.rb

delete 'user_subcriptions/destroy/:user_id/:app_id', to: 'user_subscriptions#destroy', as: 'destroy_subscription'

然后锚定到这个:

app/views/apps/_full.html.erb

<%= link_to 'stop notifications', destroy_subscription_path(session[:user_id], app.id), method: :delete %>

也许会有帮助。尝试 destroy_all

UserSubscription.destroy_all(user_id: user_id, app_id: app_id)