Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

has_many :through #49

Closed
vicoar opened this Issue · 3 comments

4 participants

@vicoar

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

Comment Model:

has_ancestry

has_many :tags

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

But doesn't work. Can you fix it?

@tilo

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
    end
  end
@Empact

@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
    end
end

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

@tilo

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

@StefanH StefanH closed this
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.