简体   繁体   English

Rails交互器:如何获得即时消息?

[英]Rails interactor : how can I have flash messages?

I am struggling with a little feature in the Interactor gem (from our friends at Collective idea). 我在Interactor gem的一个小功能中挣扎(来自我们Collective idea的朋友)。

What I want to do is to have a flash message in my interactor, just as what I would have in my controller. 我想要做的就是在交互器中有一条Flash消息,就像在控制器中一样。

Here is my create method in my controller, where I instantiate my interactor : 这是控制器中的实例化交互器的create方法:

def create
    buy_credits = BuyCredit.new(send_transactions_params)
    buy_credits.perform

    redirect_to profile_path
end

And here is the build of my interactor : 这是我的交互器的构建:

def build_transaction

    if context[:transaction][:recipient_id].nil? && context[:transaction][:recipient_type].nil?

      @transaction = user.transactions.build(context[:transaction])
      # flash[:success] = I18n.t('.bought_credits_for_client', recipient: user)

    elsif context[:transaction][:recipient_id].present? && context[:transaction][:recipient_type] == Organisation.name

      current_organisation = user.organisations.find(context[:transaction][:recipient_id])
      @transaction = current_organisation.transactions.build(context[:transaction])
      # flash[:success] = I18n.t('.bought_credits_for_organisation', recipient: current_organisation)

    else
      # flash[:error] = I18n.t('.cant_buy_credits')
    end

  end

You can see the flash message type I would like to have, they are the commented lines. 您可以看到我想要的即时消息类型,它们是注释行。

Of course, I could have something like 当然,我可能会喜欢

if interactor.success?
    redirect_to profile_path
else

in my controller, but as you can see in my commented lines, I have two "types" of success... 在我的控制器中,但是正如您在我的注释行中所看到的,我有两种成功的“类型” ...

Thanks! 谢谢!

Thanks to another colleague help, we managed to have a workaround this : we just pass the flash object (instantiated in the controller) to the context, which the Interactor receive. 感谢另一个同事的帮助,我们设法解决了这个问题:我们只是将flash对象(在控制器中实例化)传递给Interactor接收的上下文。 So the interactor add its messages to the object, which is available afterwards in the controller. 因此,交互器将其消息添加到对象,此消息随后可在控制器中使用。

Here is my context construction : 这是我的上下文构造:

def send_transactions_params
    params_to_send = {
        transaction: transaction_params,
        buyer: current_user,
        flash: flash
    }
    params_to_send
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM