0
0

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 3 years have passed since last update.

Rails DBに保存されていないデータの並び替え

Last updated at Posted at 2021-04-20

はじめに

クチコミアプリを作っています。
その中の評価機能を利用して、並べ替えの機能を作った際に詰まったこと学んだことのメモです。

table関係
(親)shops ー (子)reviews
店に対してクチコミをしますのでアソシエーションを組んでいます。

reviews
id
shop_id
content
score

scoreカラムは星5段階評価を保存しておきます。
各shopはクチコミ評価をいくつも持っていて、その平均点をmodelに書いたメソッドによってviewで表示させることができます。

class Shop < ApplicationRecord
# 省略
# 星評価の平均点を求めるメソッド
  def review_score_average
    if reviews
      reviews.average(:score).to_f.round(1)
    else
      0.0
    end
  end
end

ここで、
DBカラムに入ったデータの並べ替えは('asc', 'desc')のメソッドを使用すれば簡単にできますが
メソッドに入った中身をどの様に並べ替えればいいのか?

attr_accessorを使う

view

<%= link_to "星評価の高い店順", shops_path(sort_top_review: "true") %>

controller

if params[:sort_top_review]
  @shops = Shop.all.each do |shop|
    # averageはモデルで定義されている
    shop.average = shop.review_score_average
  end
  @shops = @shops.sort_by { |shop| shop.average }.reverse
  @shops = Kaminari.paginate_array(@shops).page(params[:page]).per(5)
end

model

  attr_accessor :average

review_countshopの属性
オブジェクトの抱えるデータのことを「属性(Attribute)」と呼ぶことがある。

attr_accessorとは

Rubyのメソッド
リファレンス

終わりに

Railsのビギナーなので間違っている点やもっといい書き方などありましたらご指摘していただければ嬉しいです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?