Index on multiple columns in Ruby on Rails

后端 未结 2 1387
感动是毒
感动是毒 2020-12-04 07:07

I\'m implementing functionality to track which articles a user has read.

  create_table \"article\", :force => true do |t|
    t.string   \"title\"
    t.         


        
2条回答
  •  执念已碎
    2020-12-04 07:18

    The order does matter in indexing.

    1. Put the most selective field first, i.e. the field that narrows down the number of rows fastest.
    2. The index will only be used insofar as you use its columns in sequence starting at the beginning. i.e. if you index on [:user_id, :article_id], you can perform a fast query on user_id or user_id AND article_id, but NOT on article_id.

    Your migration add_index line should look something like this:

    add_index :user_views, [:user_id, :article_id]
    

    Question regarding 'unique' option

    An easy way to do this in Rails is to use validates in your model with scoped uniqueness as follows (documentation):

    validates :user, uniqueness: { scope: :article }
    

提交回复
热议问题