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?

\$\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
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.