2015-11-22 30 views
0

我有一个模型Product和相关的表products & departments在数据库中。我是否需要通过IRB插入模型?

我没有Department的型号。

IRB,我可以成功地做到这一点:

p = Product.new 

但是当我这样做:

d = Department.new 

它抛出,

NameError: uninitialized constant Department

是这样发生的,因为Rails模型Department不在吗?

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

回答

2

是的错误是由于没有部门类或模型。您可以创建一个department.rb,并使用您最喜爱的编辑器从应用程序/模型目录中的活动记录继承。例如用vim,你可以做

vim app/models/department.rb 

编辑上面的文件已经下

class Department < ActiveRecord::Base 
end 

,然后用重装重装IRB会议!

1

滑轨遵循Convention over Configuration也ActiveRecord的跟随ORM(对象关系映射),并根据它:

所有models在Rails应用程序具有Singular类名称与在database一个plural名称。对于例如:在你的情况,

Department模式将参考departments数据库中的表,在这里你有departments表,但不是一个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.

现在,当您尝试初始化irbDepartment模型像

$ > d=Department.new 

这将完成是会在你app/models目录中搜索类名作为Department,如果找到这个类就将它与数据库中类似的departments表相关联,并将初始化这个object

很明显,你会发现error,因为你在app/models/Department.rb中没有声明任何类别为Department

所以,你现在需要做的是根据@shani的答案目录来声明一个类名作为你的模型Department

class Department < ActiveRecord::Base 
end 
相关问题