Rails关联数据的获取 to retrieve items from the associations


# app/models/user.rb
class User < ApplicationRecord
  has_many :groups
  has_many :grades, through: :groups
end

# app/models/grade.rb
class Grade < ApplicationRecord
  has_many :groups
  has_many :users, through: :groups
end

# app/models/group.rb
class Group < ApplicationRecord
  belongs_to :user
  belongs_to :grade
end



# Assuming you have an array of user_ids
user_ids = [1, 2, 3] # Replace with your actual user IDs

# Option 1: Using the User model and eager loading grades
grades = User.where(id: user_ids).includes(:grades).flat_map(&:grades).uniq

# Option 2: Directly querying through the Grade model with a join
grades = Grade.joins(:groups).where(groups: { user_id: user_ids }).distinct

阅读量: 10
发布于:
修改于: