When I write a slightly complicated inquiry in Active Record, I will add it as a memo so as not to forget it.
class PLine < ApplicationRecord
has_many :likes, dependent: :destroy
end
class Like < ApplicationRecord
belongs_to :p_line
end
@p_lines = PLine.select('p_lines.*', 'count(likes.id) AS favs')
.left_joins(:likes)
.group('p_lines.id')
.order('favs desc')
<% @p_lines.each do |p_line| %>
<p><%= p_line.p_line %></p>
<p><%= p_line.favs %> points</p>
<% end %>
class Mc < ApplicationRecord
has_many :videos
end
class Video < ApplicationRecord
belongs_to :mc1, class_name: 'Mc'
belongs_to :mc2, class_name: 'Mc'
end
@videos = Video.includes(:mc1, :mc2).where(mc1_id: @mc)
.or(Video.includes(:mc1, :mc2).where(mc2_id: @mc))