Adding a new has_many relationship to an existing model

I would like to add a has_many relationship to two existing tables / models in my application, and I'm not too sure how to do this?

When I did this before with the new model, the rails generate a command that processes everything for me, only with rails generate model Photo image:string hikingtrail:references she created the next migration

 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 

Now I would like to establish a connection between users and photos with each user has_many :photos .

When I create a migration to achieve this, it does not include add_index :photos, :user_id , is that what I have to do manually or is it enough to fulfill these relationships in my database?

rails g migration AddUserIdToPhotos user_id:integer

which creates ...

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

& then run ...

rake db: migrate

+7
source share
1 answer

It is enough to establish your relationship. You can add an index to increase the speed of searching records. In fact, some recommend putting the index in all foreign keys. But don’t worry about it now, I think you won’t have as many entries to use the index.

If you have already migrated everything and want to add the make make index:

  rails g migration AddIndexToUserIdToPhotos 

and inside add the index column:

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

All Articles