Getting the through items from a has_many :through :uniq relationship

Getting the through items from a has_many :through :uniq relationship

In a nutshell, I have been using the has_many :through :uniq
relationship, and I want a DRY way to list the join model objects.

Currently, my objects include taxon objects, toxin objects,
data_object objects, and taxon_toxin_citation objects (“citation” is
another word for data_object). A taxon has many data objects, has many
taxon_toxin_citations, and has many toxins through
taxon_toxin_citations. As well as a taxon causing many toxins, a toxin
can be caused by many taxa. And there are many taxon_toxin_citations
linking a given taxon with a given toxin. (If anyone is interested in
project, it is currently hosted at Google Code Archive - Long-term storage for Google Code Project Hosting.

If you want something more familiar, replace taxon with actor, toxin
with movie, data_object with character, with the possibility that an
actor may appear in a movie as more than one character.

When I’m displaying information about a taxon, I’d like to display
information about the toxins associated with the taxon, and for each
toxin, I’d like to display the citations saying that the taxon is
associated with the toxin.

Getting the list of toxins itself is easy. I have in my Taxon model

has_many :data_objects
has_many :taxon_toxin_citations
has_many :toxins, :through => :taxon_toxin_citations, :uniq=> TRUE

so all I have to do is ask for taxon.toxins

But to get the list of citations/data objects linking a specific taxon
with each toxin is a bit trickier. I currently have

toxin_citations_for_taxon = {}
taxon.toxins.each do |toxin|
taxon_toxin_citations =
TaxonToxinCitation.find_all_by_taxon_id_and_toxin_id(taxon, toxin)
toxin_citations_for_taxon[toxin] = []
taxon_toxin_citations.each do |taxon_toxin_citation|
toxin_citations_for_taxon[toxin] <<

which isn’t very DRY, and means that I have to return another

taxon.taxon_toxin_citations won’t help, as it’d mention data_objects
that link a taxon with any toxin, not just the specific one I’m
interested in. Likewise, toxin.taxon_toxin_citations won’t help, as
it’d mention data_objects that link any taxon with the specific toxin.

A few other people have asked this question, including in the comments
section of
and “Please clarify” in
. There have been some attempts to reply, but they haven’t really
answered the question.

Is there currently a better way to find the join model objects?


Andrew Grimm