Edgar
Edgar

Reputation: 503

How can i display a certain attribute in a certain table without displaying all for a current user RAILS 4

I have a student and school database tied to my rails project I have these attributes for student table:

[id,fname,lname,created_at,updated_at,school_id,user_id]

and my school table has these attributes

[id,name,address,franchise_id,created_at,updated_at]

so far I am trying to display the school name for each student that a current user may have. but when I run it, it will show all the schools for all the students of that user on each iteration of the loop. here is my index action method where the magic is supposed to happen.

  @child = Student.where(user_id:current_user.id).pluck(:school_id)
  @schoolname = School.where(id:@child).pluck(:name)

and my index page in my view:

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

my model is empty

Upvotes: 1

Views: 47

Answers (2)

Aleksandr Larionov
Aleksandr Larionov

Reputation: 126

Instead of @schoolname in your loop in view, write student.school.name If your one-to-many relationship works, this should work.

Upvotes: 1

Jonathan Goodman
Jonathan Goodman

Reputation: 371

Sorry I don't the ability to comment but I wanted to ask where you assign @students? You use it in your view but I don't see it in your controller's index method. Also @student should be student in the link_to methods at the end.

Upvotes: 0

Related Questions