我有一个student
和school
数据库绑定到我的rails项目我有学生表的这些属性:
[id,fname,lname,created_at,updated_at,school_id,user_id]
我的学校表具有这些属性
[id,name,address,franchise_id,created_at,updated_at]
到目前为止,我正在尝试为当前用户可能拥有的每个学生显示学校name
。但是当我运行它时,它将在循环的每次迭代中显示该用户的所有学生的所有学校。这是我的索引动作方法,其中应该发生魔法。
@child = Student.where(user_id:current_user.id).pluck(:school_id)
@schoolname = School.where(id:@child).pluck(:name)
和我视图中的索引页面:
<div class="container">
<h1><font color="white"><b>My students</font></b></h1>
<table class="table table-striped">
<thead>
<tr>
<th><font color="white"><b>Id</font></b></th>
<th><font color="white"><b>Fname</font></b></th>
<th><font color="white"><b>Lname</font></b></th>
<th><font color="white"><b>School</font></b></th>
<th><font color="white"><b>manage</font></b></th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @students.each do |student| %>
<tr>
<td><font color="white"><b><%= student.id %></font></b></td>
<td><font color="white"><b><%= student.fname %></font></b></td>
<td><font color="white"><b><%= student.lname %></font></b></td>
<td><font color="white"><b><%= @schoolname %></font></b></td>
<td><%= link_to 'Show', student %>
<%= link_to 'Edit', edit_student_path(student) %>
<%= link_to 'Destroy', student, method: :delete, data: { confirm:
'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<b><%= link_to 'Add Student', add_students_path(@student),
{:style=>'color:#FFFFFF;'} %></b><br/>
<b> <%= link_to 'New Student', new_student_path,
{:style=>'color:#FFFFFF;'} %></b>
</div>
我的模特是空的
答案 0 :(得分:1)
在视图中循环而不是@schoolname,写
student.school.name
如果您的一对多关系有效,那么这应该可行。
答案 1 :(得分:0)
抱歉,我无法发表评论,但我想问一下你在哪里分配@students
?您在视图中使用它,但我在控制器的索引方法中看不到它。最后@student
方法中的student
也应为link_to
。