Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: remove reference relationship

I was confused with following code in tutorial.

The goal is to remove reference key genre_id from table books

class RemoveGenreFromBooks < ActiveRecord::Migration

    def up
        remove_index :books, column: [:genre_id]
        remove_column :books, :genre_id
    end

    def down
        add_reference :books, :genre, index: true
    end

end

But I don't understand what remove_index :books, column: [:genre_id] mean

Furthermore, I didn't get that index: true in down method.

If I need to add a relationship, why I can not just type

class Addrelationship < ActiveRecord::Migration
    def change
            add_reference :books, :genre
    end
like image 288
Coda Chang Avatar asked Nov 02 '25 15:11

Coda Chang


1 Answers

As there is a method to add a referecen, there is a one to remove also - remove_reference

Syntax is: remove_reference(table_name, ref_name, options = {})

So in your case, to remove the reference of Genre :

class RemoveGenreFromBooks < ActiveRecord::Migration
  def change
    remove_reference :books, :genre, index:true, foreign_key: true
  end
end

The option foreign_key: true will also remove the foreign key from the books table.

like image 127
Ashan Priyadarshana Avatar answered Nov 04 '25 06:11

Ashan Priyadarshana