Module: Sequel::Plugins::DatasetAssociations::DatasetMethods

Defined in:
lib/sequel/plugins/dataset_associations.rb

Instance Method Summary collapse

Instance Method Details

#associated(name) ⇒ Object

For the association given by name, return a dataset of associated objects such that it would return the union of calling the association method on all objects returned by the current dataset.

This supports most options that are supported when eager loading. It doesn’t support limits on the associations, or one_to_one associations that are really one_to_many and use an order to select the first matching object. In both of those cases, this will return an array of all matching objects.

Raises:



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/sequel/plugins/dataset_associations.rb', line 71

def associated(name)
  raise Error, "unrecognized association name: #{name.inspect}" unless r = model.association_reflection(name)
  ds = r.associated_class.dataset
  sds = opts[:limit] ? self : unordered
  ds = case r[:type]
  when :many_to_one
    ds.filter(r.qualified_primary_key=>sds.select(*Array(r[:qualified_key])))
  when :one_to_one, :one_to_many
    ds.filter(r.qualified_key=>sds.select(*Array(r.qualified_primary_key)))
  when :many_to_many
    ds.filter(r.qualified_right_primary_key=>sds.select(*Array(r.qualified_right_key)).
      join(r[:join_table], r[:left_keys].zip(r[:left_primary_keys]), :implicit_qualifier=>model.table_name))
  when :many_through_many
    fre = r.reverse_edges.first
    fe, *edges = r.edges
    sds = sds.select(*Array(r.qualify(fre[:table], fre[:left]))).
      join(fe[:table], Array(fe[:right]).zip(Array(fe[:left])), :implicit_qualifier=>model.table_name)
    edges.each{|e| sds = sds.join(e[:table], Array(e[:right]).zip(Array(e[:left])))}
    ds.filter(r.qualified_right_primary_key=>sds)
  else
    raise Error, "unrecognized association type for association #{name.inspect}: #{r[:type].inspect}"
  end
  ds = model.apply_association_dataset_opts(r, ds)
  r[:extend].each{|m| ds.extend(m)}
  ds
end