#127 ActiveRecord Tricks
4-1-2018

Summary

In this episode, we look at what would seemingly be simple queries, but are more complex once you start looking into them. Using built in ActiveRecord functions, we can make the queries readable and easy to work with.
7
rails activerecord 13:21

Summary

user.rbclass User < ApplicationRecord
  belongs_to :status
  has_many :messages, dependent: :destroy
  scope :active, -> { joins(:status).merge(Status.active) }
  scope :unread_messages, -> { joins(:messages).merge(Message.unread) }
  default_scope { includes(:messages).unread_messages }
end
status.rbclass Status < ApplicationRecord
  has_many :users
  scope :active, -> { where(active: true) }
  # def self.active
  #   where(active: true)
  # end
end
message.rbclass Message < ApplicationRecord
  belongs_to :user
  scope :unread, -> { where(read: false)}
  scope :read, -> { where(read: true)}
end
Terminalrails db:create db:migrate db:seed
rails c
rails consoleUser.count
Status.count
Message.count

reload!

active_statuses = Status.where(active: true).pluck(:id)
active_users = User.where(status_id: active_statuses)
active_users = User.joins(:status).where(statuses: { active: true })

Status.active
Status.active.pluck(:id)
User.joins(:status).where(statuses: { id: Status.active.pluck(:id) })
User.joins(:status).merge(Status.active)

user = User.first
user.messages.pluck(:read)
user.messages.where(read: false)
user.messages.unread

User.active.joins(:messages).merge(Message.read)
User.active.unread_messages

User.active.scoping do
  User.last
end


brandoncc said 13 days ago:

You retrieve 37 users, not messages... Other than that, good episode.

hackvan said 3 days ago:

awesome tricks, thanks a lot!

Login to Comment