ruby - Comparing values of 2 columns from 2 tables and counting the total matches in rails -


i have 2 tables in rails application 1 of them products , other users.

in products table have created_by_id integer matches id of user created it. need display running total of products , having 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 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 rails sorry if screwing up

in app/models/user.rb file, add:

has_many :products, foreign_key: 'created_by_id' 

then can use:

current_user.products.count 

ps: it's idea call column user_id instead of created_by_id since rails can guess association column if it's in format <model_lower_case>_id.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -