Ruby-on-rails 使用 ActiveRecord 关联生成模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14959239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
generating model with ActiveRecord associations
提问by user1781472
Folks,
各位,
I am working on creating an application where I have two entities in my problem space. One entity is "biologist" and the other entity is "experiment" now one biologist can have many experiments and each experiment can have many biologist.
我正在创建一个应用程序,其中我的问题空间中有两个实体。一个实体是“生物学家”,另一个实体是“实验”,现在一个生物学家可以有很多实验,每个实验可以有很多生物学家。
I know how to create models and routes using the command line generator:
我知道如何使用命令行生成器创建模型和路由:
rails generate scaffold Biologist name:string expertise:string last_pub:text
What is the right way to add an association? Is it to go and update the model code after generation? What is unclear to me is if I add a "belongs_to" association post generation how does that reflect in the DB schema without running a migration or something? In the above example if "experiment" belongs to "biologist" then there will be a foreign key in the "biologist" table, how will that be created if I add the associations in the model class post generation. I am fairly new to rails, so I apologize if this is a naive question.
添加关联的正确方法是什么?是不是要生成后去更新模型代码?我不清楚的是,如果我在生成后添加“belongs_to”关联,它如何在不运行迁移或其他操作的情况下反映在数据库模式中?在上面的示例中,如果“实验”属于“生物学家”,那么“生物学家”表中将有一个外键,如果我在生成后的模型类中添加关联,将如何创建外键。我对 Rails 还很陌生,所以如果这是一个幼稚的问题,我深表歉意。
采纳答案by Andre Bernardes
回答by stephenmurdoch
I think you are looking for something like the following:
我认为您正在寻找以下内容:
rails g scaffold Biologist experiment:references
Read this articleby Jose Valim where he shows you how to do the above, and also add db indexes from the command line:
阅读Jose Valim 的这篇文章,他向您展示了如何执行上述操作,并从命令行添加数据库索引:
回答by bsiddiqui
I would generate a model for each each and then create a join table since you have a has many to has many relationship. If you follow convention properly, rails should understand the relationship given your join table.
我会为每个模型生成一个模型,然后创建一个连接表,因为您有许多关系。如果您正确遵循约定,rails 应该理解给定连接表的关系。
In general, if you need to modify active record relationships, you should do it in the model using a has_many or has_and_belongs_to_many relationship.
一般来说,如果您需要修改活动记录关系,您应该使用 has_many 或 has_and_belongs_to_many 关系在模型中进行。

