lib/jsonapi/resource.rb in jsonapi-resources-0.0.9 vs lib/jsonapi/resource.rb in jsonapi-resources-0.0.10
- old
+ new
@@ -259,10 +259,22 @@
raise JSONAPI::Exceptions::RecordNotFound.new(key)
end
self.new(model, context)
end
+ def find_by_keys(keys, options = {})
+ context = options[:context]
+ _models = _model_class.where({_primary_key => keys})
+
+ unless _models.length == keys.length
+ key = (keys - _models.pluck(:id).map(&:to_s)).first
+ raise JSONAPI::Exceptions::RecordNotFound.new(key)
+ end
+
+ _models.map { |model| self.new(model, context) }
+ end
+
def verify_filters(filters, context = nil)
verified_filters = {}
filters.each do |filter, raw_value|
verified_filter = verify_filter(filter, raw_value, context)
verified_filters[verified_filter[0]] = verified_filter[1]
@@ -396,10 +408,10 @@
define_method attr do
type_name = self.class._associations[attr].type
resource_class = self.class.resource_for(type_name)
if resource_class
associated_model = @model.send attr
- return resource_class.new(associated_model, @context)
+ return associated_model ? resource_class.new(associated_model, @context) : nil
end
end unless method_defined?(attr)
elsif @_associations[attr].is_a?(JSONAPI::Association::HasMany)
define_method attr do
type_name = self.class._associations[attr].type