tanya
tanya

Reputation: 2985

looping and display model's associated data

Am looping through a set of records and would like to display the model's associated data at the same time. However when trying to display the associated data, am getting an error message

Can anyone tell me What's wrong with the following code?

<% @subs.each do |submission| %>
    <%= submission.SUB_OID %>
    <%= submission.SUB_ASSAY_TYPE %>
    <%= submission.author.AUT_NAME %> -- am getting the error because of this line

<% end %>

Model: Sub has_one Author Author belongs_to Sub

If i remove this line <%= submission.author.AUT_NAME %>, the list of submissions are displayed properly, however when i include the 3rd line, i get the error 'Undefines method for AUT_NAME'.

I don't understand where the error is found.

Am a newbie and would be grateful for any suggestion provided

Upvotes: 0

Views: 361

Answers (2)

tanya
tanya

Reputation: 2985

Finally found the solution. I included the following if condition --

<% if submission.author %> <%= submission.author.AUT_NAME %> <% end %>

The reason why author name couldn't be displayed was because not all submissions have an associated entry in the authors table.

Upvotes: 0

Zepplock
Zepplock

Reputation: 29135

Either your author has no field/method named AUT_NAME or your relationship is wrong. Can you check if submission.author is nil and make sure AUT_NAME exists?

Upvotes: 1

Related Questions