Created
July 3, 2012 14:09
-
-
Save jwaldrip/3039934 to your computer and use it in GitHub Desktop.
Dynamically set unique indexes with Tire/Elastic Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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