问题
I have a model for School and Student. Their relationship is School has_many Students. I am trying to render a view where if I am on the School index page and I click "Show", it will open up a new page and display a list of students that belong to that school. Ex:
School
- Student1
- Student2
- Student3
回答1:
You can do as following:
# students controller
def index
@students = Student.scoped
@students = @students.where(school_id: params[:school_id]) if params[:school_id].present?
end
# view of the schools index
- @schools.each do |school|
= link_to "students of the school #{school.id}", students_path(school_id: school.id)
Don't hesitate to ask for explanations if you don't fully understand ;)
来源:https://stackoverflow.com/questions/23833091/show-children-of-a-parent-class-rails-4-0