问题描述
我正在实现跟踪用户阅读哪些文章的功能。
I'm implementing functionality to track which articles a user has read.
create_table "article", :force => true do |t|
t.string "title"
t.text "content"
end
这是我到目前为止的迁移:
This is my migration so far:
create_table :user_views do |t|
t.integer :user_id
t.integer :article_id
end
将始终查询user_views表以查找两列,而不会只查找其中一列。我的问题是索引应如何显示。这些表的顺序是否有所不同,是否应该有更多选择或其他选择。我的目标数据库是Postgres。
The user_views table will always be queried to look for both columns, never only one. My question is how my index should look like. Is there a difference in the order of these tables, should there be some more options to it or whatever. My target DB is Postgres.
add_index(:user_views, [:article_id, :user_id])
更新:
因为仅可能存在两列中包含相同值的一行(因为知道user_id是否已读取article_id),我应该考虑:unique选项吗?如果我没记错的话,那意味着我不必自己进行任何检查,每次用户访问文章时都只需插入一下。
UPDATE:
Because only one row containing the same values in both columns can exist (since in knowing if user_id HAS read article_id), should I consider the :unique option? If I'm not mistaken that means I don't have to do any checking on my own and simply make an insert every time a user visits an article.
推荐答案
顺序在索引中确实很重要。
The order does matter in indexing.
- 首先放置最有选择性的字段,即缩小的字段最快的行数。
- 仅当您按顺序从开始使用索引的列时才使用索引。例如,如果您在
[:user_id,:article_id]
上建立索引,则可以对user_id
或user_id和article_id
,但不在article_id
上。
- Put the most selective field first, i.e. the field that narrows down the number of rows fastest.
- 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 onuser_id
oruser_id AND article_id
, but NOT onarticle_id
.
您的迁移 add_index
行应如下所示:
Your migration add_index
line should look something like this:
add_index :user_views, [:user_id, :article_id]
关于独特选项的问题
在Rails中实现此目的的一种简单方法是使用 validates
在模型中,范围为唯一性
如下():
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 }
这篇关于Ruby on Rails中多列的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!