Created
June 9, 2013 20:54
-
-
Save bplexico/5745167 to your computer and use it in GitHub Desktop.
OSD with update_index
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 ObserverSearchData | |
attr_reader :search_data | |
def initialize(obj, search_data) | |
@obj = obj | |
@search_data = search_data | |
end | |
def update_index | |
# Would be nice to use AR here but not sure how to execut Postgres functions | |
# when inserting data like this. | |
rows = Post.exec_sql_row_count("UPDATE #{table_name} SET search_data = TO_TSVECTOR('english', ?) WHERE #{foreign_key} = ?", search_data, id) | |
if rows == 0 | |
Post.exec_sql("INSERT INTO #{table_name} (#{foreign_key}, search_data) VALUES (?, TO_TSVECTOR('english', ?))", id, search_data) | |
end | |
rescue | |
# don't allow concurrency to mess up saving a post | |
end | |
private | |
def id | |
@obj.id | |
end | |
def table_name | |
"#{object_name}_search_data" | |
end | |
def foreign_key | |
"#{object_name}_id" | |
end | |
def object_name | |
@obj.class.name.downcase | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment