ruby - How can I get all the responses by a particular user to posts on a particular topic -
i have user, micropost , response model.
the user has many microposts , has many responses.
microposts have tags using acts taggable gem.
i need find number of responses user has, microposts tagged specific tag. clear, example, how many responses has user 1 given microposts on "exercise"
there basic ruby syntax , relationship logic missing. haev in user model.
def user_responses_on_topic tag microposts = self.microposts.tagged_with(tag, :on => :tags) responses_count = 0 microposts.each |micropost| count = micropost.responses.where("user_id = :user_id", user_id: self.id).size responses_count = responses_count + count end end
its giving me value know wrong because when add responses on particular topic users value doesn't increase.
i sure there simple "ruby" way @ using
responses = user.microposts.responses
but need know how tagged logic on microposts code
i have tightened bit still not luck. individual components of code work can't whole thing work together
def user_responses_on_topic(interest) microposts = micropost.tagged_with(interest, :on => :tags, :any => true) responses ||= 0 microposts.each |micropost| responses += micropost.responses.where("user_id = :user_id", user_id: self.id).size end end
edit:
this works
def user_responses_on_topic(interest) microposts = micropost.tagged_with(interest, :on => :tags, :any => true) count = 0 microposts.each |micropost| responses = micropost.responses.size count = count + responses end count end
but there's got better rails way (this smells of php)
any ideas?
if of components working independently, might simple adding line end of method: responses
. after .each
loop executes, returns original array (not value modified within loop). since want return number stored in responses
, want variable last line of method.
Comments
Post a Comment