问题
I have:
Aulas
has_many :grades
has_many :students, :through => :grades
Students
has_many :grades
has_many :aulas, :through => :grades
Grades
belongs_to :aula
belongs_to :student
I want to show grades.name
from the conection between that Aula and a specific Student inside the Aula. This doesn't work, but you will understand what I want:
<% aula.students.each do |student| %>
<%= link_to student.name, student %>-<%= student.grade.name %>
<% end %>
Ok so, i'm inside Aula (id:68) if I do students.grades, I get the grades from all Aulas
[#<Grade id: 51, name: AA1, student_id: 22, aula_id: 68 >,#<Grade id: 52, name: AA2, student_id: 22, aula_id: 69 >,#<Grade id: 53, name: AA3, student_id: 22, aula_id: 70 >]
How do i get only the name of the grade related to this Aula (aula_id:68)?
回答1:
A student has_many :grades
(with a 's'), so when you have a student
record, you cannot call grade
(without 's') on it, because Rails don't know which grade you are looking for.
What you need to do is to call student.grades
(with a 's'), that will inform Rails that you are looking at all gradeS of this student.
But it's not finish yet, because with student.grades
you are getting all grades of this student. You have 2 solutions:
Either you want to show them all and you must loop through them, like this:
<% student.grades.each do |grade| %>
<%= grade.name %>
<br />
<% end %>
Either you are looking for one specific grade in your collection and you want to show only this one (let's imagine you are looking for the grade with id=5), you would do like this:
<%= student.grades.find(5).name %>
Also I would advise you to use the specific vocabulary, it is good so it will help you to find the correct information when you search in google for a solution. Here you are talking about connection between models, in Rails word we call it association :)
回答2:
Ok. I figured that instead of getting the name of the Grade throught Students, i can get the student through grades, so I did
<% aula.grades.each do |grade| %>
<%= link_to grade.student.name, student %>-<%= grade.name %>
<% end %>
Now it roks just fine.
来源:https://stackoverflow.com/questions/17665301/how-do-i-access-the-data-from-a-link-in-an-association