DCRubyHound DCRubyHound - 17 days ago 5x
Ruby Question

publish the nth attribute from a model

I have a model student with a subject and grade attribute. A student can have many subjects and grades, and what I'd like to do is be able to publish the 2nd or 3rd subject listed for a specific student.

For example, the user searches for a student, then clicks on the student, which brings them to a separate page listing information about that particular student (ie, student id:1). Is there code I can add to the view to list the nth item from the subject and grade attributes?

I looked online here and found similar questions, but those solutions related to the model, not the attributes. For example, one solution recommended using the limit method in the controller and another recommended using the following code:

<% firm.state_of_business.split(',').each_with_index do |state, index| %>
<td> <b>State <%= index + 1 %></b> <%= state %>

This seems to work well, when you don't have a specific model selected. When you select a particular model(ie, student id:1), this doesn't seem to work. At least not for me. Right now my code below is showing the first item. How might I get it to list subject 1 & grade 1, subject 2 & grade 2, subject 3 & grade 3, etc.. See sample code below. Please note, that I tried other solutions on here, but couldn't get them to work, which made me think that my problem might be different than the ones previously presented. Thanks for your help.

View Code


<p> Student:
<%= @student.name %>

<th> Subject </th>
<th> Grade </th>

<td><%= @student.subject %> </td>
<td><%= @student.grade %> </td>

Controller Show Method

def show
@user = current_user
@student = Student.find(params[:id])

Desired Output

Student: Matt Jones

Subject Grade
Math 95
History 90
English 91


Try adding this code:

  <%= @student.grade.split(',')[0] %>

The [0] will publish the first item in the array. [1] will publish the 2nd item, etc. That should work.