简体   繁体   English

ruby on rails:为什么没有为每个新模型关联进行迁移?

[英]ruby on rails: why isn't there a migration for every new model association?

My understanding is that relationships between tables are implemented through foreign keys. 我的理解是表之间的关系是通过外键实现的。 But when you add an association between models (belongs_to, etc), there is no change in the database schema. 但是,当您在模型之间添加关联(belongs_to等)时,数据库架构中没有任何更改。 Why is that? 这是为什么? How does rails actually know there is an association or relationship? Rails实际上如何知道存在关联或关系?

The trick here is that belongs_to, has_one, has_many only works if the appropriate keys are already in the database. 这里的窍门是,只有在数据库中已经有适当的键时,belongs_to,has_one,has_many才起作用。

The keys are usually <model>_id . 密钥通常是<model>_id

So a belongs_to relationship between post and blog requires you to have a blog_id in the posts table that you had to create using a relation. 因此,帖子和博客之间的belongs_to关系要求您在必须使用关系创建的posts表中具有blog_id。

Same goes for a has_many between blog and post. 博客和帖子之间的has_many也是如此。

class Blog < ActiveRecord::Base
  has_many :posts
end

Requires a migration that creates the blog_id foreign key in the posts table. 需要迁移才能在posts表中创建blog_id外键。

Rails will recognize the associations among the all tables by mentioning those relations in the models only, but not only with the foreign keys. Rails将仅通过提及模型中的关系来识别所有表之间的关联,而不仅限于外键。 If you don't follow the naming convention for the foreign keys, rails will loose finding the relation between the tables even you mention the relation in the models. 如果您不遵循外键的命名约定,那么即使您在模型中提到了关系,Rails也会很松散地找到表之间的关系。 Then you have to tell the foreign_key, and class names explicitly. 然后,您必须明确告诉foreign_key和类名。

class Article < ActiveRecord::Base
 has_many :comments
end 


class Comment < ActiveRecord::Base
 belongs_to :article
end

In the comments table, you have to maintain the article_id along with its own fields. 在注释表中,您必须维护article_id及其自身的字段。
Then rails will automatically assumes that article_id as foriegn_key . 然后,Rails将自动将article_id假定为foriegn_key
If you write something else(Ex: art_id ) rather article_id you have to tell as: 如果您写其他东西(例如: art_id )而不是article_id您必须说出:

class Comment < ActiveRecord::Base
 belongs_to :article, :class_name=>"Article", :foreign_key=>:art_id
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM