[RAILS] How to get only articles and transactions that you commented or messaged [includes]

Introduction

Often on sites with flea market elements such as Mercari and Jimoty Apart from the list of transactions that I have listed on My Page The list of transactions in progress is often displayed, isn't it?

Bookmarking every transaction can be a hassle, so Isn't it a useful function?

Today I would like to implement it to make it happen.

Relationship between models

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

As in the example, the article (transaction) is an article and the comment (exchange) is a comment. Each model should be associated as above.

user.rb


  has_many :articles
  has_many :comments

article.rb


  belongs_to :user
  has_many :comments

comment.rb


  belongs_to :user
  belongs_to :article

Acquisition of articles (transactions)

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

Assuming that there is a helper method current_user that returns the logged-in user as described above, Get the articles you commented on the following @article_commented_on.

home_controller.rb


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

Get all the comments posted by the user with current_user.messages and Use includes (: article) to join a table with an article.

Then, use map (&: article) to return only the article to the extracted new array. Execute uniq (a method of an array that is not a method for querying) to eliminate duplicates.

By doing this, I was able to get only the articles that I had commented on in @article_commented_on.

By doing a table join with includes (: article) You can minimize the access to the DB that occurs every time you get the article corresponding to each message.

That's all, thank you for your hard work!

Recommended Posts

How to get only articles and transactions that you commented or messaged [includes]
[Java] How to get and output standard input
How to get and study java SE8 Gold
[Ruby] How to get / select only records that are more than XX years old
How to convert A to a and a to A using AND and OR in Java
[Ruby] How to get the tens place and the ones place
[Kotlin] How to get IP address and user agent
[Swift5] How to analyze complex JSON and get the index of the element that satisfies the condition
How to replace characters that you do not understand [Principle]
When you want to explicitly write OR or AND with ransack
How to batch run JUnit and get coverage as well