Home>
I can't get it out with joins. environment

ruby 2.5.1
rails 6.0.3.2
devise 4.7.2

association
user model
  has_many:tags
  has_many:group_users
  has_many:groups,through: :group_users
group_use intermediate model
  belongs_to :group
  belongs_to :user
group model
  has_many:group_tags
  has_many:tags,through: :group_tags
  has_many:group_users
  has_many:users,through: :group_users
group_tag intermediate model
  belongs_to :group
  belongs_to :tag
tag model
  has_many:group_tags,dependent: :destroy
  has_many:groups,through: :group_tags
  belongs_to:user
Brief description of the description in the maigation file
user
  # Probably not related to this case, so I will omit it.
group_use
  t.references :group, foreign_key: true
  t.references :user, foreign_key: true
group
  # Probably not related to this case, so I will omit it.
group_tag
  t.references :group, foreign_key: true
  t.references :tag, foreign_key: true
tag
  t.references :user, foreign_key: true
Thing I want to do
tags_controller.rb
  def index
    if user_signed_in?
      @groups=Group.joins(:group_users).where(group_users:{user_id:current_user.id})
      @tags=Tag.joins(group_tags: :group_users).where(group_users:{user_id:current_user.id})
  end


See the ruby ​​code above. First,
@groups uses current_user.id and gets group information via group_users.
current_user.id→ group_user →group_id→ group
I have succeeded here.

next
I tried to get the tag information via group_users and group_tags using current_user.id in @tags.
current_user.id→ group_users →group_id→ group_tags →tag_id→ tags
I failed this.

I want to get all the tags owned by the group to which current_user belongs, but it doesn't work.
To solve the N+1 problem, I would like to use join to solve it.

If anyone knows, I would appreciate it if you could teach me.
We apologize for the inconvenience, and thank you.

  • Answer # 1

    Since the association is defined,
    @groups = current_user.groupsCan be taken with.

    @tags = Tag.joins(:groups).where("groups.user_id = ?", current_user.id)
    Can I go there?
    user_id is only in groups in these two, so
    @tags = Tag.joins(:groups).where(user_id: current_user.id)
    But it might go.