我需要一个模型才能通过 IRB 插入吗?

Do I need a model to insert through IRB?

我在数据库中有一个 Product 和关联的 tables products & departments 的模型。

我没有 Department 的模型。

IRB中,我可以成功做到:

p = Product.new

但是当我这样做时:

d = Department.new

它抛出,

NameError: uninitialized constant Department

发生这种情况是因为 DepartmentRails 模型不存在吗?

如果您已经有了 table,如何创建模型(我是否必须生成并 运行 rake db:migrate)?

yes 错误是由于没有部门 class 或型号。您可以使用您喜欢的编辑器在 app/models 目录中创建一个 department.rb 并从活动记录继承。例如 vim 你可以做

vim app/models/department.rb

编辑以上文件,使其具有以下内容

class Department < ActiveRecord::Base
end

然后使用 reload!

重新加载 irb 会话

Rails 遵循 Convention over Configuration ActiveRecord 也遵循 ORM(对象关系映射)并根据它:

Rails 应用程序中的所有 models 都有一个 Singular class 名称,在 database 中有一个 plural 名称。例如:在你的情况下,

Department 模型将引用数据库中的 departments table,其中您有 departments table 而不是 model Rails 申请中的部门。

By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class Book, you should have a database table called books. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words.

现在,当您尝试在 irb 中初始化 Department 模型时,例如

$ > d=Department.new 

它会做的是在你的 app/models 目录中搜索一个 class 名称为 Department ,如果它找到这个 class 它将把它与类似的departments table 在数据库中并将初始化此 object

它显然会抛出一个 error 因为你没有在你的 app/models/Department.rb 中声明任何 Class 为 Department

所以,您现在需要做的是根据 @shani 的回答,在您的模型目录中声明一个 class 名称为 Department

class Department < ActiveRecord::Base
end