Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 874
Holly Avatar asked Apr 08 '13 11:04

Holly


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is polymorphic association in rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

What is null false in rails migration?

The null: false parameter means this column does not allow NULL values. The default: false tells us this column will default to false whenever a value isn't specified. This is nice because we can guarantee this field will always be either true or false now. It can't be null because the database prevents it.


1 Answers

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
like image 149
Zippie Avatar answered Oct 04 '22 17:10

Zippie