3
\$\begingroup\$

I have a user, a micropost and a response model.

The user has many microposts and has many responses.

Microposts have tags using the acts as taggable gem.

I need to find the number of responses a user has, to microposts that are tagged with a specific tag. To be clear, for example, how many responses has user 1 given to microposts on "exercise"

There is some basic ruby syntax and relationship logic I am missing. This is what I have in my user

This works as a User model method

 def user_responses_on_topic(interest)
 microposts = Micropost.tagged_with(interest, :on => :tags )
 count = 0
 microposts.each do |micropost|
 responses = micropost.responses.size 
 count = count + responses
 end
 count
 end

But there's got to be a better rails way?

Marc-Andre
6,7795 gold badges39 silver badges65 bronze badges
asked Apr 29, 2015 at 19:40
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Try something like this, it would work if the #tagged_with method returns an ActiveRecord::Relation object, I don't know if you need a :user_id in there, but your code didn't hint on any, so I did the same.

Response.joins(:micropost).merge(
 Micropost.tagged_with(interest, on: :tags)
).count
answered May 1, 2015 at 10:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.