简体   繁体   中英

How can I display an nested object attribute on last in Rails 4

I have a two models: Client has_many Status in a nested relationship.

In my client index I am showing a table of all client attrs. I want to show the most recent status.

I have tried two things:

First: <%= client.statuses.last.name %> "last" in this case is not an attribute but a "last" method from the ruby api

And second: I created a Client model method

def latest_status
  current = self.statuses.last
  return current
end 

and then in the view:

<%= client.latest_status.name %>

Both return:

undefined method `name' for nil:NilClass

The caveat is that if I run debug(client.statuses.last) in the view, it prints out the attrs from the correct status.

-- EDIT User has_many :statuses Status belongs_to :user

Those are the model associations.

running debug(client.statuses.last) it returns:

--- !ruby/object:Status
attributes:
 id: 6
 name: Prospect
 value: 40000
 created_at: 2014-06-20 20:03:14.904934000 Z
 updated_at: 2014-06-20 20:03:14.904934000 Z
 client_id: 1

but I can't access the 'name' attribute with 'last'.

-- Edit 6/20 I continue to try and get this done, and I was able to achieve part of the solution but I dont think its very scaleable.

 <% client.statuses.each_with_index do |s, i| %>
        <% if i == 0 %>
          <%= s.name %>
        <% end %>
      <% end %>

By doing a simple .each_with_index loop I can get access to the first item or the last object. But if there was a lot of nested items. I feel like that would be a super big query. I only need the most recent in this case.

Your view code does not check if a client has any status, so if at least one client in your collection has no status, calling last on it will return nil and thus throw the error you see.

Solve it by either explicitly check for statuses:

client.statuses.last.name if client.statuses.any?

or in short with

client.statuses.last.try :name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM