16

我使用以下命令创建了一个 rails 应用程序:

rails new Education

现在,我正在尝试使用以下命令在 rails 中创建一个新模型:

rails generate model Education name:string

运行它时,它返回以下错误:

“Education”这个名称要么已经在您的应用程序中使用,要么由 Ruby on Rails 保留。请选择一个替代方案并再次运行此生成器。

由于我刚刚创建了一个新应用程序并且只有一个其他模型,我很难思考为什么 Rails 会保留这样的名称?

关于这个错误来自哪里以及如何解决它的任何想法?

(我尝试将名称更改为其他名称,它按预期工作。由于名称确实符合其目的,除非没有其他方法,否则我不想更改其名称!)

我将 Ruby 2.0.0 与 Rails 4.0.0 和 PostgreSQL 一起使用

4

3 回答 3

36

您不能创建与应用程序同名的模型,因为它会创建冲突的名称。当您创建应用程序时,即rails new Education它将创建一个名为Education如下的模块

module Education
  class Application < Rails::Application
  #....
  end
end

然后在文件中调用这个命名模块,例如config.ru,routes.rb等等environment.rb。因此,如果您能够创建一个同名的模型类,那么对于您是调用模型还是模块会产生歧义。

于 2013-11-04T21:19:11.343 回答
2

添加其他两个可能的原因人们可能会收到此错误。

首先,您一直在更改名称,但旧名称仍然存在,因为这是一个缓存问题。

其次,这可能是与您安装的 gem 的命名冲突。因此 gem 已经在使用您要使用的名称。

案例一::缓存问题

我收到以下错误::

The name 'Activityflow' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.

如果您在初始行中看到以下消息,则在运行rails g时。可能是缓存问题:

warning: previous definition of CALLBACK_CAMPAIGN_NAME was here
Running via Spring preloader in process 98806
      invoke  active_record

解决方案是杀死弹簧,它将释放缓存。

查找spring的进程id

$ ps -ef | grep spring
501 82388 82384   0  2:21PM ??        66:34.87 spring app    | insurance | started 16 hours ago | development mode      
501 82384     1   0  2:21PM ttys005    0:00.84 spring server | insurance | started 16 hours ago   

杀死进程例如:82384 在上述情况下

$ kill -9 82384

然后当你再次运行rails g命令时;Spring 将以新内容运行/启动,模型创建成功。

Running via Spring preloader in process 99237
  invoke  active_record
  create    db/migrate/20200518021818_create_activityflows.rb
  create    app/models/activityflow.rb
  invoke    rspec
  create      spec/models/activityflow_spec.rb

案例二::模块问题

我收到以下错误::

The name 'Workflow' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.

问题是我使用 gem gem 'workflow', '~> 2.0.2'创建模块名称 Workflow 并且不允许生成名为 Workflow 的模型。

因此,当您使用任何 gem 时要小心,并且任何 gem 中的模块名称都与模型名称匹配。

Simple way to check if module name exist is::
$ bin/rails c
[4] pry(main)> Workflow
=> Workflow
[5] pry(main)> Workflow.class
=> Module
于 2020-05-15T08:22:53.747 回答
0

Just in case it's helpful to someone else, I made a silly error and accidentally ran similar lines of code twice (they both created an 'Appointments' scaffold. It wasn't as simple as below, but I was copy/pasting something along these lines (first line succeeded but the second caused the error for obvious reasons).

rails g scaffold Appointment user:references viewer:references start_time:datetime end_time:datetime
rails g scaffold Appointment user:references viewer:references start_time:datetime end_time:datetime

Note: The error can be (again, obviously) caused by using one of rails's reserved words. An easy way to check for reserved words is https://reservedwords.herokuapp.com/words

于 2020-08-19T10:29:22.863 回答