adding a new has_many relationship to an existing model
Asked Answered
K

1

7

I would like to add a has_many relationship to two existing tables/models in my app & I'm not too sure how to di it?

When I did this before with a new model the rails generate command handled everything for me, with just rails generate model Photo image:string hikingtrail:references it created the below 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 set up a relationship between users & photos with each user has_many :photos.

When I generate a migration to achieve this it does not include the add_index :photos, :user_id, is this something I should be doing manually or are the below steps enough for setting up this relationship 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

Kaleidoscope answered 8/4, 2013 at 11:27 Comment(1)
Hi rossmc - Either you can add the line add_index :photos, :user_id manually in above migration or you can do what zippie has suggested. But in that case also you will have to write that line manually. Thanks VikramSnitch
M
6

It is enough to set up your relationship. You can add a index to improve the speed of your record searching. In fact some recommend to put a index to all the foreign keys. But don't worry about this now, i guess you are not going to have that many records to use a index.

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

 rails g migration AddIndexToUserIdToPhotos

and inside add the index column:

class AddUserIdToPhotos < ActiveRecord::Migration
  def change
    add_index :photos, :user_id
  end
end
Meridithmeriel answered 8/4, 2013 at 11:38 Comment(1)
thanks zippie, that looks to have updated my db/schema.rb file correctly & I understand it better too :)Kaleidoscope

© 2022 - 2024 — McMap. All rights reserved.