I want to fetch another association of the parent model from the intermediate table with has_many

Overview

When dealing with data using Rails, such an opportunity rarely comes (in most cases it can be replaced by another method etc.), but since it was necessary to put an association from the intermediate table for some reason, it is a memo as a memorandum I will leave it.

Prior knowledge

class User < ApplicationRecord
   has_many :group_users
   has_many :groups, through: :group_users
   has_many :comments
end

class Group < ApplicationRecord
  has_many :group_users
  has_many :users, through: :group_users
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :group
end

class GroupUser < ApplicationRecord
  belongs_to :group
  belongs_to :user
end

Suppose a class like this exists. Normally, you rarely do anything starting from an intermediate table called GroupUser, and even if you do, you can get Comments via User or Group, so there is almost no problem.

On the other hand, there were times when I wanted a list of comments that narrowed down groups and users from an instance of GroupUser due to rare circumstances such as using GraphQL or wanting data that was arranged at the timing of an association.

If you try to get through normally, the code will be as follows, for example.

class GroupUser < ApplicationRecord
  belongs_to :group
  belongs_to :user
  has_many :comments, through: :user #group is fine
end

However, with this method, the value of one of the through columns will be narrowed down, but the other column will not be narrowed down.

Regardless of which way you pass through, you can only narrow down by either user or group, and you cannot get the intended value.

solution

Then what to do is to use socpe.

class GroupUser < ApplicationRecord
  belongs_to :group
  belongs_to :user
  has_many :comments,->(group_user) { where(group_id: group_user.group_id) }, through: :user #If group, where with user
end

has_many can only take itself as a scope argument. So, by doing this, you can get a list of comments with the group_id and user_id of the group_user instance.

I hope it will be useful if you have to get it from the intermediate table as a starting point.

Recommended Posts

I want to fetch another association of the parent model from the intermediate table with has_many
I want to distinct the duplicated data with has_many through
[Ruby] I want to reverse the order of the hash table
I want to recreate the contents of assets from scratch in the environment built with capistrano
I want to mess with Permission of Windows directory from WSL (ubuntu)
I want to output the day of the week
I want to var_dump the contents of the intent
I want to play with Firestore from Rails
I want to control the start / stop of servers and databases with Alexa
[Rails] How to register multiple records in the intermediate table with many-to-many association
From the introduction of devise to the creation of the users table
I want to call a method of another class
[Java] I want to calculate the difference from the date
I was addicted to the record of the associated model
I want to know the answer of the rock-paper-scissors app
I want to display the name of the poster of the comment
I want to dark mode with the SWT app
I want to be aware of the contents of variables!
I want to return the scroll position of UITableView!
I want to redirect sound from Ubuntu with xrdp
I want to reduce the number of unnecessary queries. From considering counter_cache to introducing counter_culture.
[Ruby On Rails] How to search and save the data of the parent table from the child table
I want to expand the clickable part of the link_to method
I want to make a specific model of ActiveRecord ReadOnly
I want to change the log output settings of UtilLoggingJdbcLogger
I want to return a type different from the input element with Java8 StreamAPI reduce ()
I want to narrow down the display of docker ps
I want to temporarily disable the swipe gesture of UIPageViewController
I tried upgrading from CentOS 6.5 to CentOS 7 with the upgrade tool
I want to pass the startup command to postgres with docker-compose.
[Controller] I want to retrieve the numerical value of a specific column from the DB (my memo)
I tried to solve the problem of "multi-stage selection" with Ruby
I want to understand the flow of Spring processing request parameters
I want to return to the previous screen with kotlin and java!
I tried to build the environment of PlantUML Server with Docker
The story of Collectors.groupingBy that I want to keep for posterity
I want to limit the input by narrowing the range of numbers
I tried to check the operation of gRPC server with grpcurl
[Java] I want to perform distinct with the key in the object
I want to control the default error message of Spring Boot
I want to change the value of Attribute in Selenium of Ruby
[Android] I want to get the listener from the button in ListView
I want to display the number of orders for today using datetime.
I want to display images with REST Controller of Java and Spring!
Follow from the root node to the lower node with JavaFX ~ I know the directions ~
I want to know the JSP of the open portlet when developing Liferay
[Ruby] I want to extract only the value of the hash and only the key
I want to pass the argument of Annotation and the argument of the calling method to aspect
I tried to visualize the access of Lambda → Athena with AWS X-Ray
I want to get the field name of the [Java] field. (Old tale tone)
I translated the grammar of R and Java [Updated from time to time]
I want to find out what character the character string appears from the left
I want to introduce the committee with Rails without getting too dirty
I want you to use Enum # name () for the Key of SharedPreference
I tried to measure and compare the speed of GraalVM with JMH
After all I wanted to preview the contents of mysql with Docker ...
I want to use DBViewer with Eclipse 2018-12! !!
I want to get a list of only unique character strings by excluding fixed character strings from the file name
[Rails] [Parent-child relationship] I want to register the foreign key in the child with nil when the parent is deleted.
[Ruby] I want to make an array from a character string with the split method. And vice versa.
Use the where method to narrow down by referring to the value of another model.