【问题标题】:How do I use a model that has the same name as a gem? [duplicate]如何使用与 gem 同名的模型? [复制]
【发布时间】:2017-05-26 18:17:59
【问题描述】:

我看到了这个问题,但没有帮助:What is the fully qualified name of a model in Ruby on Rails?

我有这个代码

# create Stripe customer
customer = Stripe::Customer.create(:email => @user.email, :source => params['subscription']['token'])
stripe_subscription = Stripe::Subscription.create(:customer => customer.id, :plan => @subscription.plan)
stripe = ::Stripe.new subscription: @subscription, customer_id: customer.id, plan_id: @subscription.plan, 
  stripe_subscription_id: stripe_subscription.id, last_paid: Time.now, status: stripe_subscription.status

Stripe 是一种宝石,但它也是我模型的名称。我试过上面的::Stripe.new,也试过stripe = @subscription.build_stripe ...。他们都给出了错误

Stripe:Module 的未定义方法 `new'

【问题讨论】:

  • 我建议为您的Stripe 模型创建一个命名空间以避免与Stripe 模块发生任何冲突。
  • 两者不能使用相同的名称。您可以尝试重命名模型类 CustomModelName
  • @Gerry 如何创建命名空间?我尝试了module MyModule; class Stripe < ApplicationRecord,但是当我尝试使用MyModule::Stripe.new 在控制台中创建一个新实例时,它给出了NameError: uninitialized constant MyModule
  • @Chloe 你把文件移到models/my_model 文件夹了吗?

标签: ruby-on-rails namespaces


【解决方案1】:

你不能。顶级命名空间中不能存在同名的模块和类。如果您确实确实让 Rails 加载了您的 Stripe 模块,您的应用程序会因类型错误而崩溃,并抱怨您试图将 Stripe 的类型从模块更改为类。

【讨论】:

  • 它不会因类型错误而崩溃。它加载并运行到代码 sn-p 的最后一行。它确实可以识别Stripe:: 模块,例如Stripe::Customer
  • @Chloe 我说如果你真的让 Rails 加载你的模型,它会崩溃。 Rails 甚至不知道您有一个名为Stripe 的模型。它从不加载它。当 Rails 在你的代码中遇到 Stripe 时,它已经被定义为一个模块,所以 Rails 的自动加载器实际上并没有去寻找你的模型,所以你的模型甚至永远不会被加载。您需要重命名模型或将其放入模块中。我建议重命名,因为“Stripe”不是一个描述性很强的模型名称。这是什么,付款?一个帐户?交易? 必须有一个更好的名字。
猜你喜欢
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2013-03-24
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
相关资源
最近更新 更多