ruby-on-rails - 如何在 rails 服务对象中显示 flash 消息

标签 ruby-on-rails ruby service-object

我想将服务对象添加到我的 Controller 中。是否有机会将 flash 消息包含到该服务对象中?

user_stocks_controller

class UserStocksController < ApplicationController
  def create
    @user_stock = UserStocksCreator.new(current_user, params).call
    redirect_to my_portfolio_path
  end
end

服务对象user_stocks_creator

class UserStocksCreator
  def initialize(current_user, params)
    @current_user = current_user
    @params = params[:stock_ticker]
  end

  def call
    stock = Stock.find_by_ticker(params)
    if stock.blank?
      stock = Stock.new_from_lookup(params)
      stock.save
    end
    @user_stock = UserStock.create(user: current_user, stock: stock)
    flash[:success] = "Stock #{@user_stock.stock.name} was successfully added to portfolio"
  end

  private

  attr_accessor :current_user, :params
end

使用这段代码我有一个错误:

undefined local variable or method `flash'

最佳答案

flash 方法仅在 Controller 中可用。当你想在服务对象中设置 flash 时,你需要将 flash 传递给服务对象。

# in the controller
def create
  @user_stock = UserStocksCreator.new(current_user, params, flash).call
  redirect_to my_portfolio_path
end

# in the service
class UserStocksCreator
  def initialize(current_user, params, flash)
    @current_user = current_user
    @params = params[:stock_ticker]
    @flash = flash
  end

  def call
    # unchanged...
  end

  private

  attr_accessor :current_user, :params, :flash
end

关于ruby-on-rails - 如何在 rails 服务对象中显示 flash 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56137245/

相关文章:

ruby-on-rails - Rails 远程表单 collection_select onchange 错误

ruby - 使用 Ruby 向子进程发送消息

ruby-on-rails - Rails 3:DataObjects::SQLError——我如何阻止它们在 *warnings* 上产生错误?

javascript - Rails 4 Backbone 的事件顺序需要加载

ruby-on-rails - 如何在 Rails 中生成连接表

ruby-on-rails - Rails 应用程序所需的最少文件数量是多少?

mysql - crontab 执行 rails 命令

ruby-on-rails - rails 命名空间服务对象

ruby-on-rails - Rails 4 在服务对象中包含 Helper

ruby-on-rails - Rails 销毁操作不会删除