0

I am building application – simple grade book and got stuck in one thing. I have model files for User, Grade and Test where:

class Grade < ActiveRecord::Base
   belongs_to :user
   belongs_to :test
end

class Test < ActiveRecord::Base
   has_one :grade, dependent: :destroy
   validates :topic, presence: true
end

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  has_many :grades, dependent: :destroy
end

Grade table contains user_id, test_id and result.

The idea is this: Each User from user#show page can go only to his/her grades from certain subject (I made only two). Teacher can see grades of every created student. And here is the thing: when I'm logged as teacher (admin) and going from certain User page to Grades page my URL changes like this:

/user/7 -> /grades/7?subject=History

For User’s id everything is clear but in my DB, I don’t have Grade with id=7. So question is this:

How can I access this id ‘7’ from grade link to compare it with user_id in Grade table to display grades of this user only. Tried like below, but got empty table:

<% @grades.each do |g| %>
    <tr>
        <% if Test.find(g.test_id).subject == 'History' && User.find(params[:id]) == g.user_id %>
            <td><%= Test.find(g.test_id).topic %></td> 
            <td><%= Test.find(g.test_id).date %>
            <td><%= g.result %></td>
        <% end %>
    </tr>
<% end %>

So generally I am looking for something like this_url(params[:id]). Do you have any ideas? Please help!

x6iae
  • 4,074
  • 3
  • 29
  • 50
wbucko
  • 95
  • 1
  • 9

1 Answers1

3

The first thing I'll advice is to have as little logic as possible on your view.

That being said: If you want to get the grades of a particular user, since grades has a relationship with users, you should be able to just call user.grade directly.

Also, you don't need to do <%= Test.find(g.test_id).topic %> in your view, instead of calling Test.find(g.test_id).topic, you can just call g.test.topic.

So, to give a total refactor, you can have the following in your controller:

def <the name of your controller action>
  @user = User.find(params[:id])
  @grades = @user.grades.where(subject: 'history')
end

and then in your view:

<% @grades.each do |g| %>
  <tr>
    <td><%= g.test.topic %></td> 
    <td><%= g.test.date %>
    <td><%= g.result %></td>
  </tr>
<% end %>

and everything should work just fine.

Note: you can follow this post to get the name of your subject from the URL and include it dynamically into your controller query, but I will advise to pass the subject as a params as well ( /grades/7/history ), as opposed to passing it as a query ( /grades/7?subject=History ).

Community
  • 1
  • 1
x6iae
  • 4,074
  • 3
  • 29
  • 50