LoginSignup
0
0

More than 3 years have passed since last update.

自分がコメント、メッセージした記事や取引のみ取得する方法【includes】

Last updated at Posted at 2020-11-06

はじめに

よくメルカリや、ジモティーなどと言ったフリマ要素のあるのサイトでは
マイページに自分が出品した取引一覧とは別に、
やりとり中の取引一覧がよく表示されていますよね

取引の度にブックマークするとなかなか面倒くさいので、
何気に重宝する機能なのではないでしょうか

今日はそれを実現するよう実装をしていきたいと思います

モデル間の関係

スクリーンショット 2020-11-06 20.06.54.png

例のように記事(取引)をarticle、コメント(やりとり)をcomment、とし
各モデルは上記のようなアソシエーションにします。

user.rb
  has_many :articles
  has_many :comments
article.rb
  belongs_to :user
  has_many :comments
comment.rb
  belongs_to :user
  belongs_to :article

記事(取引)の取得

application_controller.rb
  helper_method :current_user

  private

  def current_user
    if session[:user_id]
      @current_user ||= User.find_by(id: session[:user_id])
    end
  end

上記のようなログイン中のユーザーを返り値とするヘルパーメソッドcurrent_userがあるとしたうえで、
以下の@article_commented_onに自分がコメントした記事を取得していきます。

home_controller.rb
  def mypage
    @article_commented_on = current_user.messages.includes(:article).map(&:article).uniq
  end

current_user.messagesでユーザーが投稿したコメント全てを取得し、
includes(:article)でarticleとテーブル結合を行います。

そしてmap(&:article)にてarticleのみを抜き出した新たな配列に返し、
uniq(クエリー用のメソッドではない配列のメソッド)を実行し重複を消します。

こうすることで@article_commented_onには自分がコメントしたことのある記事のみを取得することができました。

includes(:article)でテーブル結合を行うことによって、
各messageに対応したarticleを取得する度に発生するDBへのアクセスを最低限に減らすことができます。

以上です、お疲れ様でした!

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