【问题标题】:Rails 4: Model Logic - Counting Items by a UserRails 4:模型逻辑 - 按用户计数项目
【发布时间】:2016-09-22 19:17:06
【问题描述】:

一个简单的问题:

假设我有一个用户(设计)和项目模型。 current_user 可以创建和标记他的项目。如果他这样做了,is_marked 的值将更改为 true
这行得通。

但是我如何才能收到current_user 标记的项目数?

我是这样想的:

current_user.joins(:items).where(user.id: current_user.id)
# How can I count the number of items marked?
# In addition, I don't know if it is the right solution to use joins. Correct me if I am wrong.

协会: 用户:has_many :items 项目:belongs_to :user

提前感谢您的任何回答!如果您需要更多信息,请告诉我。

【问题讨论】:

  • 这些模型之间有关联吗?
  • current_user.items.where(is_marked: true).count
  • @Bartek Gładys 已编辑帖子。

标签: ruby-on-rails ruby ruby-on-rails-4 devise rubygems


【解决方案1】:

我想您在用户和项目之间有关联?如果是,您可以:

current_user.items.where(is_marked: true).count

【讨论】:

  • 工作,完美。我会尽快接受的:)
  • 您还可以在项目上创建一个范围并使用它。
【解决方案2】:

扩展 Barket Gladys 的回答,您可能会发现创建项目范围并使用它很有用。

在 items.rb 模型文件中:

scope :marked, -> { where(:is_marked => true) }

然后使用范围如下:

current_user.items.marked.count

【讨论】:

  • 感谢您的回答!这就是我最后肯定会做的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 2011-10-06
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多