【问题标题】:How do you call a controller action from a model in rails如何从 Rails 中的模型调用控制器操作
【发布时间】:2018-12-14 04:48:19
【问题描述】:

我有一个 Rails 应用程序,我正在尝试使用在文本字段中找到 @ mentions 的模型文件,然后我希望它使用 after_create 回调通知 @mentioned

class Post < ApplicationRecord
  after_create :notifiy_users

  def notifiy_users
    mentioned_users.each do |user|
      Notification.create!(recipient: user,
                           actor: self.user,
                           action: 'mentioned',
                           notifiable: self)
    end
  end

  def mentions
    @mentions ||= begin
      regex = /@([\w]+)/
      matches = body.scan(regex).flatten
    end
  end

  def mentioned_users
    @mentioned_users ||= User.where(username: mentions)
  end
end

local_env 上,这可以工作并且通知已创建并保存,但是当我推送到生产环境时,这就像从未调用过after_create 一样,并且我没有从 notify_users 方法中得到任何回报。

任何帮助或建议以更好的方式处理此问题将不胜感激。

【问题讨论】:

  • 在生产中,你的mentioned_users很可能是空的。
  • 你想从模型哪里调用控制器动作??
  • 从模型中调用控制器动作听起来是个坏主意。你为什么要这样做?

标签: ruby-on-rails ruby model-view-controller


【解决方案1】:

从模型内部调用控制器操作违反了MVC。模型动作应该只处理与数据相关的逻辑,所有动作都应该留在控制器中。

相反,您应该从控制器中调用回调:

class PostController < ApplicationController
  after_action :notify_users, only: [:create]

  ...

  def notify_users
    @post.mentioned_users.each do |user|
      Notification.create!(recipient: user,
                     actor: @post.user, 
                     action: 'mentioned',
                     notifiable: self)
    end
  end

end     

您的模型将如下所示:

class Post < ApplicationRecord

  def mentions
    @mentions ||= begin
      regex = /@([\w]+)/
    matches = self.body.scan(regex).flatten
   end
  end

  def mentioned_users
    @mentioned_users ||= User.where(username: self.mentions)
  end

end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2011-04-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多