【发布时间】:2013-11-24 00:08:23
【问题描述】:
我很新,并且正在学习数据库的东西以及 Rails。现在我有以下声明:
def tournaments_played
@tournaments_played = Tournament.count
end
使用这些模型:
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
has_many :tournaments, through: :profile
class Profile < ActiveRecord::Base
belongs_to :user, class_name: "User"
has_many :tournaments
class Tournament < ActiveRecord::Base
belongs_to :profile
belongs_to :user
显然 tours_played 正在返回每条记录的计数。我只想要那个用户的锦标赛。如果需要,我可以粘贴方案!
【问题讨论】:
-
哪个用户是“那个”用户?如果您想要锦标赛,那么您可以使用
@user.tournaments.count,其中@user已分配给特定用户。此外,您不需要在 Profile 模型中使用class_name: "User"。
标签: sql ruby-on-rails database activerecord