Created
May 14, 2018 09:41
-
-
Save lingceng/2bf51609987ef15390fc751e2863202f to your computer and use it in GitHub Desktop.
Rails connect another database tips.
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
# app/models/concerns/convert_time_zone.rb | |
module ConvertTimeZone | |
extend ActiveSupport::Concern | |
included do | |
date_columns = columns.select { |column| column.sql_type == 'datetime' }.map(&:name) | |
convert_time_zone date_columns | |
def timestamp_attributes_for_update | |
[:last_updated] | |
end | |
end | |
module ClassMethods | |
def convert_time_zone(*fields) | |
fields = fields.flatten.map(&:to_s) | |
fields.each do |field| | |
define_method(field.to_sym) do | |
attributes[field] && (attributes[field] - 8.hour) | |
end | |
end | |
define_method(:write_attribute) do |attr, value| | |
converted = if attr.to_s.in?(fields) && value.present? | |
(value.is_a?(String) ? Time.zone.parse(value) : value) + 8.hour | |
else | |
value | |
end | |
super(attr, converted) | |
end | |
end | |
end | |
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
# app/models/data_record.rb | |
class DataRecord < ActiveRecord::Base | |
self.abstract_class = true | |
self.table_name_prefix = "data_" | |
self.pluralize_table_names = false | |
self.inheritance_column = :_type_disabled | |
establish_connection("data_source_#{Rails.env}".to_sym) | |
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
# app/models/data/team.rb | |
class Data::Team < DataRecord | |
include ConvertTimeZone | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment