我正在尝试删除用户订阅,但是当我点击这样的时候,所有对current_user的订阅都会被删除,而不是只有被定位的订阅。似乎唯一有效的是原始sql
conn = ActiveRecord::Base.connection
conn.execute(%Q{
delete from user_subscriptions
where user_id = #{user_id}
and app_id = #{app_id}
})
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
...
<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>
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
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'
class UserSubscription < ActiveRecord::Base
belongs_to :user
belongs_to :app
end
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 }
class User < ActiveRecord::Base
has_many :user_subscriptions
has_many :apps, through: :user_subscriptions
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
答案 0 :(得分:2)
也许它会有所帮助。尝试destroy_all
UserSubscription.destroy_all(user_id: user_id, app_id: app_id)
答案 1 :(得分:1)
您需要使用DELETE
动词而不是GET
:
的routes.rb
delete 'user_subcriptions/destroy/:user_id/:app_id', to: 'user_subscriptions#destroy', as: 'destroy_subscription'
并锚定于此:
应用程序/视图/应用/ _full.html.erb
<%= link_to 'stop notifications', destroy_subscription_path(session[:user_id], app.id), method: :delete %>