【问题标题】:How to add callback 'after_create' in Controller which is in module?如何在模块中的 Controller 中添加回调“after_create”?
【发布时间】:2020-08-14 10:21:00
【问题描述】:

假设我有类似的控制器

module Module
  class UsersController < ApplicationController
    before_action :set_user, only: %i[show]
    after_create :somemethod

   private

    def set_user
      @user = User.find(params[:id])
    end
  end
end

#Model
class User < ApplicationRecord

end

所以当我这样写时,set_user 不起作用,我的意思是它不会创建用户对象。 你能帮我做同样的事情吗? 提前致谢。

【问题讨论】:

  • 我有一种预感,除了回调之外,您还面临其他一些问题。你能多描述一下并添加一些代码吗(多于少)
  • set_user 方法可能有问题,因为它似乎被调用了(除非您看到类似 undefined method set_user for #&lt;SomeController:0x000055b9410c5648&gt; 的内容。请分享该代码或错误消息。
  • @Pascal 我认为它没有错误。我也遇到了这样的错误。
  • 所以显示所有代码。 :set_user 方法在哪里?
  • 也发布你的一些方法,因为由于你的一些方法中的错误,创建可能会回滚。

标签: ruby-on-rails ruby module controller


【解决方案1】:

控制器中没有after_create。您可以调用after_actionbefore_action 作为过滤器来环绕控制器方法:https://guides.rubyonrails.org/action_controller_overview.html#filters

见:

module Module
  class UsersController < ApplicationController
    after_action :somemethod

    def show
    end

    private

    def somemethod
      puts "This will work"
    end
  end
end

after_create 或任何更新/创建/提交回调仅适用于模型:https://guides.rubyonrails.org/active_record_callbacks.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    相关资源
    最近更新 更多