marcbowes/gheed — comment on commit 42940b5258ab47930e68728077e943dd8d3642eb
File:  line 0
By marcbowes:

This is the problem.

```ruby
# In the controller
@deliveries = current_user.deliveries
```

```ruby
# In the view
@deliveries.each do |delivery|
delivery.state
end %>
```

What you want to display is the view. To do this, you need to:

```ruby
# in delivery.rb
def state
delivery_state.name
end
end
```

This yields the classic N+1 query problem unless you remember to go back to the controller and `includes(:delivery_state)` for this and each place we references deliveries where we also need the state's name. Offhand, the most obvious place would be creating deliveries where we want to insert it with the state 'queued' by default.

The gist I posted is a window into a fix which uses `Rails.cache` to cache the name to id mappings. It would need to be extended to also cache the id to name mappings, but this is trivial. You would then just write the following codes for either use-case:

```ruby
# create a delivery in state 'queued'
delivery = Delivery.new(:user_id => current_user, :delivery_state_id => DeliveryState.queued)
```

```ruby
# display a delivery's state name
delivery.state # under the hood this would call `DeliveryState.from_id(delivery_state_id)`
```