module Associatable

Public Instance Methods

assoc_options() click to toggle source
# File lib/laris/larisrecord/associatable.rb, line 67
def assoc_options
  @assoc_options ||= {}
end
belongs_to(assoc_name, options = {}) click to toggle source
# File lib/laris/larisrecord/associatable.rb, line 42
def belongs_to(assoc_name, options = {})
  options = BelongsToOptions.new(assoc_name, options)
  assoc_options[assoc_name] = options

  define_method(assoc_name) do
    klass = options.model_class
    foreign_key_value = send(options.foreign_key)
    primary_key = options.primary_key

    klass.where(primary_key => foreign_key_value).first
  end
end
has_many(assoc_name, options = {}) click to toggle source
# File lib/laris/larisrecord/associatable.rb, line 55
def has_many(assoc_name, options = {})
  options = HasManyOptions.new(assoc_name, self.name, options)

  define_method(assoc_name) do
    klass = options.model_class
    foreign_key = options.foreign_key
    primary_key_value = send(options.primary_key)

    klass.where(foreign_key => primary_key_value)
  end
end
has_one_through(assoc_name, through_name, source_name) click to toggle source
# File lib/laris/larisrecord/associatable.rb, line 71
  def has_one_through(assoc_name, through_name, source_name)
    define_method(assoc_name) do
      through_options = assoc_options[through_name]
      through_klass = through_options.model_class
      through_table = through_klass.table_name
      through_fk_value = send(through_options.foreign_key)
      through_pk = through_options.primary_key

      source_options = through_klass.assoc_options[source_name]
      source_klass = source_options.model_class
      source_table = source_klass.table_name
      source_fk = source_options.foreign_key
      source_pk = source_options.primary_key

      result = DBConnection.execute(<<-SQL, through_fk_value)
        SELECT
          #{source_table}.*
        FROM
          #{through_table}
        JOIN
          #{source_table}
        ON
          #{through_table}.#{source_fk} = #{source_table}.#{source_pk}
        WHERE
          #{through_table}.#{through_pk} = ?
      SQL

      source_klass.new(result.first)
    end
  end