mysql - 我如何在某个表中显示某个属性而不显示当前用户 RAILS 4 的所有属性

标签 mysql ruby-on-rails ruby ruby-on-rails-4

我有一个 studentschool 数据库绑定(bind)到我的 rails 项目 我有 student 表的这些属性:

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

我的模型是空的

最佳答案

在你的 View 循环中写下@schoolname,而不是 student.school.name 如果您的一对多关系有效,那么这应该有效。

关于mysql - 我如何在某个表中显示某个属性而不显示当前用户 RAILS 4 的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29932405/

相关文章:

ruby-on-rails - 显示用户可能没有的数据的最佳实践

mysql - SQL 获取小于/介于十进制值 (13,6) 之间

mysql - root 用户访问被拒绝,mysql 数据库

php - 24小时值(value)

ruby-on-rails - 单表继承替代方案

ruby-on-rails - 使用 Rails 运行多个后台并行作业

ruby - Sinatra 和 Datamapper 无法将数组保存为数据类型对象

mysql - 我们可以在 mysql 中使用 sum of in group_concat 吗?

ruby-on-rails - 为什么我们需要在这个 Rails try block 中使用问号?

ruby-on-rails - 在 ruby​​ 中按 block 添加