Damon Delcoro
Damon Delcoro

Reputation: 11

How to retrieve and output the last record by foreign id?

I have 2 Models in my application. Project & Note. A project has_many notes. This all works great but on the projects index page.html.erb I would like to show the last note for a project.

My question is how do I retrieve this and then display it, on the index screen?

Upvotes: 0

Views: 37

Answers (1)

Shiko
Shiko

Reputation: 2624

You can get the last note using project.notes.last. In your view, add below :

<% projects.each do |project| %>
  <% last_note = project.notes.last %>
  <%= last_note.note unless last_note.nil? %> # get last note per project if it exists
<% end %>

Upvotes: 1

Related Questions