Pergunta

I have added a validation like this one to my model:

validates :name, uniqueness: {scope: user_id}

And added an add_index like this on my migration:

add_index(:posts, :name)

But I just read on the rails api page the part about data integrity.

And I was wondering if I will have any integrity errors on my models, so my question is: should I rewrite my indexes as?

add_index(:posts, [:name, :user_id]), unique: true

Thanks all,

Foi útil?

Solução

The data integrity you're talking about can be enforced at 2 levels as you probably already know: at the application level and at the database level.

At the application level: the validation you added. At the database level: the index you suggested

You already set up the first one. So, as long as everything goes through your Rails model to be saved in db, you won't have any db integrity issue.

However, if other third-party applications may write to your db, it is not a bad idea to enforce the uniqueness also at the db level.

And even if the first one is sufficient, it is not a bad idea neither to set up the second.

In addition, if you happen to often query the name associated with a user_id, it is actually better to use the add_index(:posts, [:name, :user_id]), making your queries a bit faster.

Outras dicas

yes - that would be a good idea. Your model validation implies a composite primary key.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top