title: Rails validations: Multi-field uniqueness: Unnecessary queries in the database
body: <p>I have a Rails 4.2/Ruby 2.2 application, where I have a <strong>users</strong> table and a <strong>servers</strong> table. A server "belongs to" a user (foreign keyed by <strong>user_id</strong>), and a server name must be unique to a particular user.   It looks like this in PostgreSQL: </p>
  
  <pre><code>CREATE TABLE users (
    id integer NOT NULL,
    name character varying(255)
  );
  
  CREATE TABLE servers (
    id integer NOT NULL, 
    name character varying(255),
    user_id integer NOT NULL
  );
  
  ALTER TABLE servers ADD CONSTRAINT servers_user_id_fk FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE RESTRICT; 
  
  ALTER TABLE servers ADD PRIMARY KEY (user_id, name);
  </code></pre>
  
  <p>This SQL will prevent me from adding a server referring to an invalid user, and it will prevent a given user from using a server name more than once. </p>
  
  <p>The Rails models look something like this:</p>
  
  <pre><code>class User &lt;&lt; ActiveRecord::Base
    has_many :servers
  end
  
  class Server &lt;&lt; ActiveRecord::Base
    belongs_to :user, foreign_key: "user_id"
  
    validates :must_have_unique_name_and_user_id, on: :create
  
    def must_have_unique_name_and_user_id
      name_count = Server.where(user_id: user_id, name: name).count
      if name_count &gt; 0
        errors[:base] &lt;&lt; "Server name is already taken for name #{name}, and user #{user.name}"
    end
  end
  </code></pre>
  
  <p>My problem is that when I run the test suite with code coverage, <strong>must_have_unique_name_and_user_id()</strong> gets called hundreds of times because these two models are foundational to my overall data model. Each one of those validation calls results in a database query to check to see if a server name is unique to a user. </p>
  
  <p>This seems like a lot of unnecessary work just to ensure valid data in Rails for something which the database will not allow no matter what. </p>
  
  <p>Is it possible to structure the Rails validations so that the error message I have in the Rails validation <strong>must_have_unique_name_and_user_id()</strong> is displayed if a user tries to have a duplicated (user_id, name) combination for a server, but such that the Rails validation is not run every single time?</p>