Self referencing model: how to join columns from join table in childrens as well

Dear everyone,

I’d like to ask two questions, how can I optimize my performance of my current model?

I’d like to use the information from translations table as it is (all columns) …

=> Translation(id: integer, word_id: integer, conversion_id: integer, created_at: datetime, updated_at: datetime, user_id: string, unit_id: integer, last_learned: date, missed: integer, learned: integer)

… and merge it to any translations/conversions children of Word.

My model getter self_with_translations should attach it to all translations/conversions but using join.

Second thing would be to optimize the check for in unit_ids section for only select unit_ids once and not have many selects.

The program is right here:

I appreciate any help,

kind regards,


Code below:

class Word < ActiveRecord::Base

has_and_belongs_to_many :conversions, class_name: “Word”,

join_table: “translations”,

association_foreign_key: “conversion_id”

def available_units=(unit_ids_as_array)

@available_units = unit_ids_as_array


def available_units

@available_units || []


def with_enriched_data

#@FIXME join merge instead of calling sep.

meta = Translation.where(word_id:

fix for deleted units, don’t deliver them!

self.available_units ={|u| } # @FIXME Cache or call only one time

unit_id = meta.unit_id if self.available_units.include? meta.unit_id

enrich with attrs unit_id, …

attributes.merge(unit_id: unit_id, missed: meta.missed)


def self_with_translations(targetlang_id={})

conversions = self.conversions.where(language_id: targetlang_id).map do |c|



attributes.merge(translations: conversions)