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
Holly
source share