I want to add service objects in to my controller. However destroy action seems didn't work properly - basically it doesn't delete anything just redirect to the page without flash message.
user_stock_destroyer.rb
class UserStocksDestroyer
def initialize(current_user, params, flash)
@current_user = current_user
@params = params[:id]
@flash = flash
end
def call
stock = Stock.find(params)
@user_stock = UserStock.where(user_id: current_user.id, stock_id: stock.id).first
@user_stock.destroy!
flash[:notice] = 'Stock successfully removed'
end
private
attr_reader :current_user, :params, :flash
end
user_stocks_controller.rb
class UserStocksController < ApplicationController
def destroy
UserStocksDestroyer.new(current_user, params, flash)
redirect_to my_portfolio_path
end
end
You're creating the object but you're not calling call
, the method that does the work
def destroy
UserStocksDestroyer.new(current_user, params, flash).call
redirect_to my_portfolio_path
end