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.

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