Gugubaight Gugubaight - 2 months ago 5
Ruby Question

Rails 4: Model Logic - Counting Items by a User

One quick question:

Lets assume I have an User (Devise) & Item Model. The current_user can create and mark his items. If he does, the value of

is_marked
changes to
true
.

That works.


But how can I receive the number of marked Items by the
current_user
?

I thought something like this:

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.


Associations:
User:
has_many :items

Item:
belongs_to :user


Thanks in advance for any answer! Please tell me if you need additional information.

Answer

I suppose you have associations between users and items ? If yes, you can simply:

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