-1

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

komal sharma
  • 195
  • 1
  • 3
  • 12

1 Answers1

1

Instead of validating the uniqueness of :name, you need to validate the uniqueness of :name, :user_id

validates_uniqueness_of :name, :scope => :user_id

(I just searched for how to do this in Rails. I don't know rails, only how databases work)

Apparently in rails 4:

validates :name, :uniqueness: { scope: :user_id }

This is kind of dumb because honestly it should be symmetric, because you are just trying to create a uniqueness constraint on the model that is equivalent to saying that there is a compound key in the database (:name, :user_id).

alternative
  • 12,703
  • 5
  • 41
  • 41