2016-09-22 26 views
2

一個快速的問題:軌道4:型號邏輯 - 由用戶計數物品

讓我們假設我有一個用戶(設計)&產品型號。 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

你有beetwen這些模型的關聯? –

+0

'current_user.items.where(is_marked:true).count' – fanta

+0

@BartekGładys編輯後。 – Gugubaight

回答

2

我想你有用戶和項目之間的關聯?如果是的話,你可以簡單地說:

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

完美的作品。我會盡快接受:) – Gugubaight

+0

您也可以在物品上創建範圍並使用它。 –

1

擴展在Barket乃迭的答案,你可能會發現上創建一個項目範圍和使用。

在items.rb模型文件:

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

然後使用範圍如下:

current_user.items.marked.count 
+0

感謝您的回答!這就是我最終會做的:) – Gugubaight