【问题标题】:Rails active record query basicsRails 活动记录查询基础知识
【发布时间】: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


【解决方案1】:

我打算给你一个更具体的答案,但你没有说明你是如何设置你的锦标赛模型的,所以我不能给你实际的代码。

看看这个tutorial。您将在那里找到问题的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多