Rails 4:模型逻辑 - 用户计算项目

时间:2016-09-22 19:17:06

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

一个简单的问题:

假设我有一个用户(设计)&项目模型。 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

提前感谢您的回答!如果您需要其他信息,请告诉我。

2 个答案:

答案 0 :(得分:2)

我想你用户和物品之间有关联吗?如果是,您可以简单地说:

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

答案 1 :(得分:1)

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

在items.rb模型文件中:

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

然后使用范围如下:

current_user.items.marked.count