Skip to content

Instantly share code, notes, and snippets.

@AlexVKO
Created May 3, 2016 20:28
Show Gist options
  • Save AlexVKO/67dd3bc4f4f68a78ef3b36264baa5216 to your computer and use it in GitHub Desktop.
Save AlexVKO/67dd3bc4f4f68a78ef3b36264baa5216 to your computer and use it in GitHub Desktop.
Model property
class Property < ApplicationRecord
# => Relations
belongs_to :customer
has_many :notes, as: :notable
has_many :work_orders
# => Serializer and accessors
serialize :general_informations, HashSerializer
store_accessor :general_informations, :has_dogs, :gate_code
serialize :address, HashSerializer
store_accessor :location,:address,
:city,
:state,
:zip
# => Delegations
delegate :company, to: :customer
# => Geolocation
geocoded_by :full_address, :latitude => :lat, :longitude => :lng
after_validation :geocode
# => Validations
validates :customer_id, presence: true
# validates :has_dogs, presence: true
validates :city, presence: true
validates :address, presence: true
validates :state, presence: true
# validates :zip, presence: true
# validates :lat, presence: true
# validates :lng, presence: true
# => Scoped queries
scope :all_by_customer, ->(customer_id) {
where(customer_id: customer_id) if customer_id
}
scope :all_by_company, ->(company_id) {
joins(:customer).where(customers: {company_id: company_id}) if company_id
}
scope :nearby_by_id, ->(property_id) do
property = find(property_id)
near(property.cordinates, 10, order: 'distance')
end
# => Active record Methods
enum address_type: [ :residential, :comercial ]
enum status: [ :active, :archived ]
# Helpers
def is_billing_address
customer.billing_address_id == id
end
def last_visit_at
Time.now
end
def full_address
"#{address}, #{city}"
end
def to_s
"#{full_address} (#{customer.name})"
end
alias_method :label, :to_s
def cordinates
"#{lat}, #{lng}"
end
def directions
{
lat: lat,
lng: lng
}
end
end
# == Schema Information
#
# Table name: properties
#
# id :integer not null, primary key
# customer_id :integer
# general_informations :jsonb default("{}"), not null
# address_type :integer
# location :jsonb default("{}"), not null
# bodies_of_water :jsonb default("[]"), not null
# created_at :datetime not null
# updated_at :datetime not null
# status :integer default("0"), not null
# lat :float
# lng :float
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment