Rails what's difference in unique index and validates_uniqueness_of

前端 未结 3 2338
难免孤独
难免孤独 2021-02-15 02:43

Firstly, can anyone explain how unique index works in databases?

Suppose I have a User model with a name column and I add a unique index on it

3条回答
  •  自闭症患者
    2021-02-15 03:08

    As for the uniqueness goes,

    Uniqueness validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index on both columns in your database.

    Also, if you just have validates_uniqueness_of at model level then you would be restricted to insert duplicate records from rails side BUT not at the database level. SQL inject queries through dbconsole would insert duplicate records without any problem.

    When you say that you created a foreign key with index on "user_id" in "posts" table then by default rails only creates an index on it and NOT a unique index. If you have 1-M relationship then there is no point in unique index in your case.

    If you had unique: true in your posts table for "user_id" then there is no way that duplicate records with same "user_id" would go through

提交回复
热议问题