how to view all associated data among models

人走茶凉 提交于 2019-12-11 15:01:13

问题


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

I have the following data models:

User

has_many :student_groups, dependent: :destroy

Student_Group

belongs_to :user
has_many   :students, dependent: :destroy

Student

belongs_to :student_group

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

Thanks for any help!


回答1:


Try this

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



回答2:


Now I have came up with a better option for you, you can use has_many :through association :

User

has_many :student_groups, dependent: :destroy
has_many :students, through: :student_groups

Student_Group

belongs_to :user
has_many   :students, dependent: :destroy

Student

belongs_to :student_group

Now you will be able to get all students that are associated with any given user's student_groups like this:

@user = User.find(params[:user_id])
@user.students

it will look more cleaner. Thanks




回答3:


Suppose you have @user = User.find(params[:id]) than try this one:

@students = []
@user.student_groups.each |sg|
  @students << sg.students
end


来源:https://stackoverflow.com/questions/17834631/how-to-view-all-associated-data-among-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!