LoginSignup
1
1

More than 1 year has passed since last update.

【Rails】orderメソッドが効かないとき

Last updated at Posted at 2022-06-27

1対多のアソシエーションの場合の並び替えで躓いたのでメモφ(´・ω・`)メモメモ

今回は、記事に対するコメントを新着順で並び替えです。

まず、新着順にするために下記のように、
コントローラーにorder(created_at: :desc)を追記しました。
しかし、並び替えされず・・・

app/controllers/post_controller.rb
def show
  #~~省略~~
  @comment = Comment.new
  @comments = @post.comments.order(created_at: :desc)
end

解決方法

1) postモデルに-> { order(created_at: :desc) }を追加
※dependent: :destroyの前に置くとエラーになりました。

app/models/post.rb
 class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, -> { order(created_at: :desc) }, dependent: :destroy
  #~~省略~~
end

2) commentモデルにoptional: trueを追加

app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :post, optional: true
 #~~省略~~
end

3) Postコントローラーにincludes(:comments)を追加

app/controllers/post_controller.rb
def show
  #~~省略~~
  @comment = Comment.new
  @comments = @post.comments.includes(:comments)
end

以上の手順でコメントを新着順に並び替えることができました!

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