1

I'm creating a movie rental app in Rails. I'm trying to create a view that displays each movie in the database, and the count of available copies on hand.

I have a postgresql database that has an inventory table with columns: inventory_id, film_id, checkout_status. It has data like:

inventory_id 1, film_id 1, available
inventory_id 2, film_id 1, available
inventory_id 3, film_id 1, available
inventory_id 4, film_id 2, available
inventory_id 5, film_id 2, available
inventory_id 6, film_id 2, available
inventory_id 7, film_id 2, available

My models are setup so that film has_many inventory, and inventory belongs_to film.

I have an inventory controller that is defining my index action as:

    def index
      @inventory = Inventory.all
    end 

in my view, I'm trying to iterate through my inventory table (accessing info from film table as well) to show the film's title, description, and the count of available copies. This is what I've got so far:

    <% @inventory.each do |i|
      <%= i.film.title %>
      <%= i.film.description %>
    <% end %>

It's giving me a list of films like this:

Movie 1, description 1
Movie 1, description 1
Movie 1, description 1
Movie 2, description 2
Movie 2, description 2
Movie 2, description 2
Movie 2, description 2

What I'm going for is something like this:

Movie 1, description 1, count: 3
Movie 2, description 2, count: 4

I've tried a bunch of things, but nothing is working and I'm now at a loss. Can anybody help?

pbybel
  • 13
  • 3

1 Answers1

0

Try this:

def index
  @inventory = Inventory.select('distinct(film)')
end 

This will bring only the films that are actually on the inventory, and only one record per film.

And:

<% @inventory.each do |i|
  <%= i.film.title %>
  <%= i.film.description %>
  <%= Inventory.where(film_id: i.film_id).count %>
<% end %>

The counting could be improved, maybe with a counter cache on the association, like is sugested here: Rails order by results count of has_many association

Zavitoski
  • 403
  • 5
  • 11