banditKing
banditKing

Reputation: 9579

Can I have an index on 4 columns and set it to unique in a Rails app postgresql db?

I would like to set a index based on 4 columns in my db in order to ensure fast lookups and also to ensure that no two rows have the identical entries in ALL the 4 columns. Thus ensuring uniqueness based on the 4 columns. I know this can be done in other languages and frameworks, but can it be done in rails?

I have seen the following command to set an index in rails:

add_index "users", ["email"], :name => "index_users_on_email", :unique => true

However, can something similar be done for more than 1 column?

Also if this cannot be done for more than 1 column, how do people handle uniqueness based on multiple columns in rails then?

Upvotes: 0

Views: 131

Answers (1)

Bryan Marble
Bryan Marble

Reputation: 3533

Yes, you can create an index on multiple columns in Rails.

add_index users, [email, col1, col2, col3], :name => "my_name", :unique => true 

should work. As long as you specify the name you should be good.

PostgreSQL (not sure about MySQL) has a character limit on constraint names, so when using add_index for multiple columns, make sure you're either giving a custom name, or that your column names are short enough to fit under the limit, because otherwise the auto-generated index_users_on_col1_and_col2_and_col3 could screw things up for you.

Upvotes: 3

Related Questions