我在rails应用程序中有2个表,其中一个是Products
,另一个是Users
。
在产品表中,我有一个created_by_id
,它是一个与创建它的用户ID匹配的整数。我需要显示正在运行的所有产品,但这样做有问题。
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
我是新来的人,所以对不起,如果我搞砸了
在app/models/user.rb
文件中,添加:
has_many :products, foreign_key: 'created_by_id'
然后,您可以使用:
current_user.products.count
PS:最好调用该列user_id
而不是调用该列,created_by_id
因为Rails可以猜测关联列是否为format <model_lower_case>_id
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句