Skip to content
This repository

has_many :through #49

Closed
vicoar opened this Issue May 16, 2011 · 3 comments

4 participants

vicoar StefanH Tilo Ben Woosley
vicoar
vicoar commented May 16, 2011

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
tilo commented May 04, 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
    end
  end
Ben Woosley
Empact commented May 04, 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
    end
end

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

Tilo
tilo commented May 07, 2012

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

StefanH StefanH closed this May 07, 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.