vendredi 3 juillet 2015

How to set uniqueness in rails model?

I have 1:N model relationship between User and Post where as post model has following fields

name
is_deleted

Model class for Post:

class Post < ActiveRecord::Base
 belongs_to :user
 validates_uniqueness_of :name
 ....

In above case when we will save the Post.name it should be unique in whole database. But according to my scenario I want to apply Post.name unique validation for each user.

Let's take a scenario:

user1 can have @post.name = `first` but it can't save the another post with the name of 'first'

user2 can still save the `post.name` = first

How can I implement that validation in post model

Aucun commentaire:

Enregistrer un commentaire