Skip to content

has_many :through #49

vicoar opened this Issue May 16, 2011 · 3 comments

4 participants

vicoar commented May 16, 2011

I had comment (with ancestry) and tags.
Given a comment I need to access all the tags of children.
I have

Comment Model:


has_many :tags

has_many :subtags,
:through => :children,
:source => :tag,
:uniq => true

But doesn't work. Can you fix it?

tilo commented May 5, 2012

instead of trying to model this with an ActiveRecord relation, you can write your own method inside the Comment class:
(this works also for STI sub-classes)

  class Comment
    def subtags
      self.children.collect{|x| x.tags}.try{:sort}.try(:uniq).try(:flatten)  # or use descendants instead of children
Empact commented May 5, 2012

@tilo, I think that code won't work as children.collect will return an array of tag arrays. And you don't need the trys, as collect will always return at least an empty array.

If you're using ruby 1.9.2+ you can do something like this:

class Comment
    def subtags
      children.flat_map{|x| x.tags}.uniq.sort  # or use descendants instead of children

Otherwise, just do collect, flatten, uniq, sort in that order.

tilo commented May 7, 2012

@Empact my code worked for me. Thanks for pointing out flat_map - much easier on the eyes.

@StefanH StefanH closed this May 7, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.