Rails 模型名称与包含的 gem 冲突 [英] Rails Model name conflict with included gem

查看:61
本文介绍了Rails 模型名称与包含的 gem 冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们一直在模拟我们的电子邮件工作取得成功,直到我们真正将 SendGrid Gem 包含在我们的工作人员的顶部

We've been mocking up our email jobs with success until we actually included our SendGrid Gem at the top of our worker

require 'sendgrid-ruby'
include SendGrid

class Notifications::WelcomeWorker
  include Sidekiq::Worker

  def perform(email_id)

    emailAddr = Email.find(email_id)
    ...
  end
end

问题似乎是因为 SendGrid 在 (Email) 中具有相同的模型

The problem seems to arise because SendGrid has the same model within (Email)

从而生成消息

undefined method `find' for SendGrid::Email:Class

我尝试通过 ApplicationRecord::Email 调用 Email 以更具体地了解具体情况,但无济于事.

I've tried calling Email via ApplicationRecord::Email to be more context specific but to no avail.

所有 SO 和其他指南通常都会更改我们的模型名称,但我觉得必须有更好的方法.需要明确的是,我们正在运行 Rails 5,所以我想知道它是否有更新来解决这个我根本没有发现的问题.

All the SO and other guides generally go with change our model name, but I feel like there must be a better way. To be clear we are running Rails 5 so I'm wondering if theres been an update in it to address this issue which I simply haven't found.

推荐答案

include SendGrid 罪魁祸首.

它将 SendGrid 模块中的所有常量添加到当前模块(这可能是顶层),因此您可以使用 SendGrid 的类而无需前缀,例如只是 Email.new 而不是 SendGrid::Email.new.

It adds all constants from the SendGrid module to the current module (which is probably the top level), so you can use SendGrid's classes without prefix, e.g. just Email.new instead of SendGrid::Email.new.

缺点是它还会干扰您现有的常量.

The downside is that it also messes with your existing constants.

您可以将其包含在特定模块下:

You can either include it under a specific module:

class Notifications::WelcomeWorker
  include Sidekiq::Worker
  include SendGrid

  # ...
end

然后,Email 解析为 Sendgrid::Email 并且 ::Email 解析为您的顶级 Email> 班级.

Then, Email resolves to Sendgrid::Email and ::Email resolves to your top-level Email class.

或者您可以简单地删除 include SendGrid 行并使用 SendGrid:: 前缀.

Or you could simply remove the include SendGrid line and use the SendGrid:: prefix.

这篇关于Rails 模型名称与包含的 gem 冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆