一个简单的问题:
假设我有一个用户(设计)&项目模型。 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
提前感谢您的回答!如果您需要其他信息,请告诉我。
答案 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