Skip to content

Instantly share code, notes, and snippets.

@jwaldrip
Created July 3, 2012 14:09
Show Gist options
  • Save jwaldrip/3039934 to your computer and use it in GitHub Desktop.
Save jwaldrip/3039934 to your computer and use it in GitHub Desktop.
Dynamically set unique indexes with Tire/Elastic Search
class Contact < ActiveRecord::Base
# Elastic Search
include Tire::Model::Search
include Tire::Model::Callbacks
# Unique Index
include Tire::UniqueIndex
unique_index :account_id
# Relationships
belongs_to :account
end
module Tire
module UniqueIndex
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
private
def unique_index(field)
define_method :set_unique_index do
self.class.index_name self.send(field)
end
define_method :fetch_unique_index do
set_unique_index unless new_record?
end
before_save :set_unique_index
after_initialize :fetch_unique_index
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment