I have a Query model:
class Query < ActiveRecord::Base
belongs_to :test
end
which is related to a Test model:
class Test < ActiveRecord::Base
has_one :query
end
I would like to display all of the queries in a list along with the Test description that they are associated to. I’ve put the following into my Query controller file for the index method:
Query.includes(:test).each do |query|
end
My questions are two-fold:
-
Is the above correct?
-
What code can I use in the “view” field of my my index.html.erb file in order to display the description of the test that is associated with the Query? If I write
<td><%= query.test.description %></td>
I get the following error: “undefined method `description’ for nil:NilClass”
Thanks.
Your loop shouldn’t be inside your controller. Your Queries controller should just contain the following:
and your queries/index view should contain the loop:
You should further refractor this by using partials and Rail’s built-in support for rendering collections:
app/views/queries/index.html.erb:
app/views/queries/_query.html.erb:
app/views/tests/_test.html.erb: