[RUBY] Active Record, complex queries

When I write a slightly complicated inquiry in Active Record, I will add it as a memo so as not to forget it.

Sort by the number of records in the related table

class PLine < ApplicationRecord
  has_many :likes, dependent: :destroy

class Like < ApplicationRecord
  belongs_to :p_line
@p_lines = PLine.select('p_lines.*', 'count(likes.id) AS favs')
                .order('favs desc')
<% @p_lines.each do |p_line| %>
  <p><%= p_line.p_line %></p>
  <p><%= p_line.favs %> points</p>
<% end %>

There are multiple related columns, and the value of the variable matches one of them. I want to include all related columns.

class Mc < ApplicationRecord
  has_many :videos

class Video < ApplicationRecord
  belongs_to :mc1, class_name: 'Mc'
  belongs_to :mc2, class_name: 'Mc'
@videos = Video.includes(:mc1, :mc2).where(mc1_id: @mc)
               .or(Video.includes(:mc1, :mc2).where(mc2_id: @mc))

Recommended Posts

Active Record, complex queries
What is Rails Active Record?
Frequently used methods in Active Record
[Ruby on Rails] About Active Record callbacks