Question: I have 2 tables in my rails application one of them is `Products` and the other is `Users`.

In the products table I have a `created_by_id` which is an integer that matches the id of the User who created it. I need to display a running total of the Products and I am having an issue doing so.

```
class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  def ensure_logged_in
    unless current_user
      flash[:alert] = "Please log in"
      redirect_to root_path
    end
  end

  def totalprods
   Product.all.joins(:users).where("created_by_id LIKE current_user.id").count
  end

  helper_method :current_user

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

end

```

i'm new to rails so i am sorry if i am screwing something up

Answer: 
In your `app/models/user.rb` file, add:

```
has_many :products, foreign_key: 'created_by_id'

```

Then you can use:

```
current_user.products.count

```

PS: It's a good idea to call that column `user_id` instead of `created_by_id` since Rails can guess the association column if it's in the format `<model_lower_case>_id`.
Based off your question you could do it one of 2 ways 
The Long Way:

```
def totalProds
   count = 0
   @products = Product.all
   @products.each do |product|
      count = count + 1
   end
   return count
end

```

If your models are setup properly you should be able to use the short method which would be

```
def totalProds
   @products = Product.all
   count = @products.count
   return count
end

```

The second method would be the preferred unless you had to do something in conjunction with the count being added to your counter. Ruby offers a lot of small functions like this already.