我是否需要手动为 HABTM 连接表创建迁移? [英] Do I need to manually create a migration for a HABTM join table?
问题描述
我现在正在努力让 HATBM 正常工作.我有一个被打败的 scanario:文章和标签.我认为这里应该使用 HABTM,因为它是多对多的关系.但是我不知道我是否应该手动创建一个连接表(在这种情况下是 articles_tags).
I'm struggling now to get HATBM working correctly. I have a beaten scanario: articles and tags. I presume, HABTM should be used here, since it is a many-to-many relationship. I don't know however if I should manually create a join table (articles_tags in this case).
我的代码目前如下:
class Article < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :articles
end
当我运行迁移时,没有创建第三个表.另外,我想补充一点,我的第三个表不承载任何域逻辑,只是盲目分配.
When I run the migrations, no 3rd table is created. Also, I would like to add that my third table doesn't bear any domain logic, just blind assignment.
我使用的是 Rails 2.2.2
I'm using Rails 2.2.2
推荐答案
您应该在其中一个表的迁移中执行此操作,或者如果已运行这些迁移,则应在单独的迁移中执行此操作:
You should do this in a migration of one of the tables, or in a separate migration if those migrations have been ran:
create_table :articles_tags, :id => false do |t|
t.references :article, :tag
end
add_index :articles_tags, [:article_id, :tag_id]
这将为您创建表和 :id =>false
告诉 Rails 不要向这个表添加 id 字段.还有一个索引,可以加快对这个连接表的查找.
This will create the table for you and the :id => false
tells Rails not to add an id field to this table. There's an index also, which will speed up lookups for this join table.
您也可以为此生成一个模型 (ArticlesTag) 并执行以下操作:
You could also generate a model (ArticlesTag) for this and do:
# article.rb
has_many :articles_tags
has_many :tags, :through => :articles_tags
# tag.rb
has_many :articles_tags
has_many :articles, :through => :articles_tags
# article_tag.rb
belongs_to :tag
belongs_to :article
然后在从 script/generate modelarticles_tag
调用生成的迁移中创建表.
And then create the table in the migration generated from the script/generate model articles_tag
call.
这篇关于我是否需要手动为 HABTM 连接表创建迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!