2013-04-08 53 views
7

我想在我的应用程序中为两个现有表格/模型添加has_many关系&我不太确定如何去做它?将一个新的has_many关系添加到现有模型

当我与一个新的模型轨道生成命令处理了我的一切,只有rails generate model Photo image:string hikingtrail:references这样做过它创建下面的迁移现在

class CreatePhotos < ActiveRecord::Migration 
    def change 
    create_table :photos do |t| 
     t.string :image 
     t.references :hikingtrail 

     t.timestamps 
    end 
    add_index :photos, :hikingtrail_id 
    end 
end 

我想建立与users & photos之间的关系每个userhas_many :photos

当我生成一个迁移来实现它,它不包括add_index :photos, :user_id,这是我应该手动做的事情还是下面的步骤足以在我的数据库中建立这种关系?

rails g migration AddUserIdToPhotos user_id:integer

它创建...

class AddUserIdToPhotos < ActiveRecord::Migration 
    def change 
    add_column :photos, :user_id, :integer 
    end 
end 

&然后运行...

耙分贝:迁移

+1

喜rossmc - 要么你可以添加一行 add_index :照片,:user_id 手动在上面的迁移或您可以做zippie建议。但是在这种情况下,您还必须手动编写该行。谢谢Vikram – vikram 2013-04-08 11:40:57

回答

6

这足以建立的关系。您可以添加索引来提高记录搜索的速度。实际上有些人建议把索引放到所有的外键上。但现在不用担心,我想你不会有那么多记录使用索引。

如果您已经迁移了一切,并想添加一个索引凑合:

rails g migration AddIndexToUserIdToPhotos 

和内添加索引列:

class AddUserIdToPhotos < ActiveRecord::Migration 
    def change 
    add_index :photos, :user_id 
    end 
end 
+1

谢谢zippie,看起来已经正确更新了我的'db/schema.rb'文件,并且我也更了解它:) – Holly 2013-04-08 12:01:49

相关问题