如何查看模型之间的所有关联数据 [英] how to view all associated data among models

查看:39
本文介绍了如何查看模型之间的所有关联数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一段时间寻找这个,但我不确定如何问我想知道的东西,我认为这是我最大的问题:p

I've spent awhile searching for this but I'm not really sure how to ask what I want to know and I think that's my biggest problem here :p

我有以下数据模型:

用户

has_many :student_groups, dependent: :destroy

学生组

belongs_to :user
has_many   :students, dependent: :destroy

学生

belongs_to :student_group

我想查看所有给定用户的 student_groups 中的所有学生 - 如何执行此操作?目前,我的student#index 路线如下:

I want to view all students across all a given user's student_groups - how to do this? At the moment, my students#index route is as follows:

student_group_students GET    /student_groups/:student_group_id/students(.:format)          students#index

students#index 似乎是放置它的合乎逻辑的位置,但它也需要一个 student_group_id - 这意味着它只是给定 student_group 中学生的索引.根据我的代码,这是有道理的,但有没有办法为 student#index 视图覆盖它?例如,在学生控制器中的 student#index 操作中,类似于:

students#index seems like the logical place to put this, but it also calls for a student_group_id - meaning it's only the index of students in a given student_group. Based on my code, that makes sense but is there a way to override it for the students#index view? For example, in the students#index action in the students controller, something like:

def index
  @students = @student_group.all.students
  ...
end 

感谢您的帮助!

推荐答案

试试这个

如果要检索特定用户的学生,则需要通过 url 发送用户 ID.需要自定义routes.rb

If you want to retrieve a students for a particular users, then you need to send the user id through url. Need to customize the routes.rb

@user_group_ids = User.find(params[:user_id]).student_groups.map(&:id)

@students = Student.where('student_group_id IN (?)', @user_group_ids)

else 如果您正在查找当前用户,则

else if you are finding for the current user, then

@user_group_ids = current_user.student_groups.map(&:id)

@students = Student.where('student_group_id IN (?)', @user_group_ids)

这篇关于如何查看模型之间的所有关联数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆