ruby-on-rails - 如何在 Rails 服务对象中显示 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
使用此代码,我有一个错误:
未定义的局部变量或方法“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
推荐阅读
- javascript - 警报不适用于 React Hooks 和 Bootstrap
- lambda-calculus - SK基础 组合逻辑的完整性
- python - 以表格格式打印嵌套字典
- reactjs - 如何通过反应设置 fireabse 规则?
- python - 在该时间点检索用户的谷歌日历
- javascript - 如何将 ArrayBuffer 流转换为视频?
- python-sphinx - doxygenfile 的替代方案,用于使用呼吸渲染文件描述
- python - 自动化 tkinter 文件对话以进行功能测试
- bash - Bash 执行一个循环
- html - CSS 注释会影响/禁用 CSS 规则吗?