2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】孫モデルの数が最大の子モデルの要素を取得する方法(maximum,maxを使わず、sortで実装する)

2
Last updated at Posted at 2020-04-01

やりたいこと

食べログ的なサービスを作っているとして、
いいねが最も多い投稿の画像を、お店の画像として表示したい

まえがき

今回やりたかったことが、RailsのmaximumメソッドやRubyのmaxメソッドを使ってもどうしてもできなかった。(やり方あったら教えてください。)
ので、自分でメソッドを作りました。

アイデアとしては、最大のものを取ってくるというよりも、**「並べ替えて端っこを持ってくる」**ってだけです。

sortメソッドを使いました。
自分的に少し詰まったのでまとめておきます。
誰かの役に立てることを願って。

状況

機能

食べログ的なサービスを作っている。機能としては、

  • お店に対して
  • ユーザーが
  • 画像を投稿する
  • ユーザーは投稿に対していいねできる

テーブル

テーブル名 カラム1 カラム2 カラム3 カラム4
Shop id name
User id name
Post id user_id shop_id image
Like id user_id post_id

アソシエーション

  • Shop has many posts
  • User has many posts
  • User has many likes
  • Post has many likes

(belongs toは省略)

概要

  • ControllerでShopモデルのインスタンス取得
  • Viewでmost_liked_imageメソッドを使って画像を表示
  • Modelでmost_liked_imageメソッドを定義

この順に説明します。

ControllerでShopモデルのインスタンス取得

.rb
@shop = Shop.find(params[:id])

とか。
変数@shopにShopモデルのインスタンスが入れる。

Viewでmost_liked_imageメソッドを使って画像を表示

.erb
<%= image_tag @shop.most_liked_image.to_s %>

most_liked_imageメソッドについては次項で説明します。

Modelでmost_liked_imageメソッドを定義

most_liked_imageメソッドで、最もいいねが多い投稿の画像を取得することを考える

models/shop.rb
class Shop < ApplicationRecord
  has_many posts, dependent: :destroy

  def most_liked_imege
    sorted_posts = self.posts.sort { |a,b| a.likes.count <=> b.likes.count }
    sorted_posts.last.image
  end
end

以上.
間違ってたらごめんなさい。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?