Composite index - M:N in Ruby on Rails

Asked

Viewed 147 times

0

I need to add a double index to the ratio N to N, from the table courses_internships. would be more or less like this: add_index[:course_id, :internship_id].

However, when I created the link table, the index was separated by the columns, not as the index being both. How can I reverse this situation?

And ah, I use the method has_and_belongs_to_many

  • Ok, you need to remove the old index and create another one right ?

1 answer

1


Your new index will be something like: (if you don’t need it to be unique, just remove the unique: true of the line).

add_index :courses_internships, [:course_id, :internship_id], unique: true

To remove and add Dexes, you can use the following command:

$ rails g migration remove_separated_indexes_and_add_new_to_course_internships

and then edit the Migration class with something like:

class RemoveSeparatedIndexesAndAddNewToCourseInternships < ActiveRecord::Migration
  def change
    remove_index :courses, :course_id
    remove_index :internships, :internship_id
    add_index :courses_internships, [:course_id, :internship_id], unique: true
  end
end

Valeuu!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.