Skip to content

Instantly share code, notes, and snippets.

@thiagosil
Last active August 7, 2020 18:56
Show Gist options
  • Save thiagosil/4018992775516f77061930b355e7ea84 to your computer and use it in GitHub Desktop.
Save thiagosil/4018992775516f77061930b355e7ea84 to your computer and use it in GitHub Desktop.
rails g model User name:string
rails g model AddEmailToUser
rails db:rollback
rails db:migrate:status
save(validate: false)
valid?
invalid?
validates :terms_of_service, acceptance: true
validates :email, confirmation: true
validates :private_label, exclusion: { in: %w(debito_cef itau_uniclass) }
validates :name, format: { with: /\A[a-zA-Z]+\z/}
validates :private_label, inclusion: { in: %w(debito_cef itau_uniclass) }
validates :token, length: { in: 6..20 }
validates :paid_amount, numericality: true
validates :rule, presence: true
validates :rule, uniqueness: true
validates :customer_id, uniqueness: { scope: %i[recipient price formatted_created_at], message: I18n.t(:duplicated_reload) }
validates :rule, uniqueness: true, on: :create
validates :status, inclusion: { in: %w[ok nok in_progress confirmation_requested cancellation_requested] }, if: -> { status }
# Verificando o resultado da validacao
customer.errors
# Custom Validator
validate do |order|
Validators::InstallmentsValidator.new(order).validate
end
module Validators
class InstallmentsValidator < ActiveModel::Validator
def initialize(order)
@order = order
end
def validate
installments = @order.installments
payment_source_type = @order.payment_source_type
@order.errors[:base] << I18n.t(:installments_payment_source_invalid) if
installments.present? && !payment_source_type.eql?(ConstantsHelper::CREDIT_CARD)
end
end
end
# Callbacks
before_validation :set_default_values, on: :create
class Limit < ApplicationRecord
belongs_to :rule
belongs_to :context_group
end
class ContextGroup < ApplicationRecord
has_many :limits, dependent: :destroy
end
# Exemplo has_many through
class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
end
# has_and_belongs_to_many
class ProductOffering < ApplicationRecord
has_and_belongs_to_many :customer_segments
has_and_belongs_to_many :marketing_segments
has_and_belongs_to_many :sales_channels, dependent: :delete_all
end
# has_one
class Customer < ApplicationRecord
has_one :customer_profile, dependent: :destroy
end
# polymorphic
class PaymentSourceRole < ApplicationRecord
belongs_to :payment_source, polymorphic: true, autosave: true
end
# Find
User.find(10)
User.first
User.last
User.find_by(email: 'thiago@m4u.com.br')
# Batch
# Nao faca isso
User.all.each do |user|
NewsMailer.weekly(user).deliver_now
end
# Batchs de 1000
User.find_each do |user|
NewsMailer.weekly(user).deliver_now
end
# Find in batches
Invoice.find_in_batches do |invoices|
export.add_invoices(invoices)
end
# Conditions
Client.where("orders_count = ?", params[:orders])
# Nao faca isso, nao e seguro
Client.where("orders_count = #{params[:orders]}")
# Hash Conditions
# Igualdade
Client.where(locked: true)
# Range
Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
# In
Client.where(orders_count: [1,3,5])
# Not
Client.where.not(locked: true)
# Or
Client.where(locked: true).or(Client.where(orders_count: [1,3,5]))
# Order
Client.order(:created_at)
Client.order(created_at: :desc)
# Select
Client.select(:viewable_by, :locked)
# Limit
Client.limit(5)
Client.limit(5).offset(30)
# Join
Category.joins(:articles)
# N+1 Include
# Errado
clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
end
# Certo
clients = Client.includes(:address).limit(10)
clients.each do |client|
puts client.address.postcode
end
# Scope
class Customer < ApplicationRecord
scope :by_uuid, (->(uuid) { where(uuid: uuid) })
scope :msisdn, (->(msisdn) { where(msisdn: msisdn) })
end
# DynamicFinder
Customer.find_by_msisdn('21989557944')
Client.find_or_create_by(first_name: 'Andy')
nick = Client.find_or_initialize_by(first_name: 'Nick')
# Pluck
Client.where(active: true).pluck(:id)
# Exists?
Customer.exists?(msisdn: '21989557944')
Customer.count
# Explain
User.where(id: 1).includes(:articles).explain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment