lib/softwear/auth/model.rb in softwear-lib-1.5.9 vs lib/softwear/auth/model.rb in softwear-lib-1.5.13
- old
+ new
@@ -86,22 +86,48 @@
end
# ======================================
# ====================
# Not a fully featured has_many - must specify foreign_key if the association doesn't match
- # the model name.
+ # the model name, through is inefficient.
# ====================
def has_many(assoc, options = {})
assoc = assoc.to_s
- class_name = options[:class_name] || assoc.singularize.camelize
- foreign_key = options[:foreign_key] || 'user_id'
+ if through = options[:through]
+ source = options[:source] || assoc
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{assoc}
- #{class_name}.where(#{foreign_key}: id)
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{assoc}
+ #{through}.flat_map(&:#{source})
+ end
+ RUBY
+
+ else
+ class_name = options[:class_name] || assoc.singularize.camelize
+ foreign_key = options[:foreign_key] || 'user_id'
+
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{assoc}
+ #{class_name}.where(#{foreign_key}: id)
+ end
+ RUBY
+ end
+ end
+
+ # ====================
+ # Pretty much a map function - for activerecord compatibility.
+ # ====================
+ def pluck(*attrs)
+ if attrs.size == 1
+ all.map do |user|
+ user.send(attrs.first)
end
- RUBY
+ else
+ all.map do |user|
+ attrs.map { |a| user.send(a) }
+ end
+ end
end
def arel_table
@arel_table ||= Arel::Table.new(model_name.plural, self)
end