Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
remove individual update methods
#remove these methods from SearchObserver
def self.update_posts_index(observer_search_data)
update_index(observer_search_data.object_name, observer_search_data.id, observer_search_data.search_data)
end
def self.update_users_index(observer_search_data)
update_index(observer_search_data.object_name, observer_search_data.id, observer_search_data.search_data)
end
def self.update_categories_index(observer_search_data)
update_index(observer_search_data.object_name, observer_search_data.id, observer_search_data.search_data)
end
#Updated update_index method
def self.update_index(observer_search_data)
table_name = "#{observer_search_data.object_name}_search_data"
foreign_key = "#{observer_search_data.object_name}_id"
# 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} = ?", observer_search_data.search_data, observer_search_data.id)
if rows == 0
Post.exec_sql("INSERT INTO #{table_name} (#{foreign_key}, search_data) VALUES (?, TO_TSVECTOR('english', ?))", observer_search_data.id, observer_search_data.search_data)
end
rescue
# don't allow concurrency to mess up saving a post
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment