lib/jsonapi/resource.rb in jsonapi-resources-0.5.0 vs lib/jsonapi/resource.rb in jsonapi-resources-0.5.1

- old
+ new

@@ -594,11 +594,11 @@ def _primary_key @_primary_key ||= _model_class.respond_to?(:primary_key) ? _model_class.primary_key : :id end def _as_parent_key - @_as_parent_key ||= "#{_type.to_s.singularize}_#{_primary_key}" + @_as_parent_key ||= "#{_type.to_s.singularize}_id" end def _allowed_filters !@_allowed_filters.nil? ? @_allowed_filters : { id: {} } end @@ -619,11 +619,14 @@ def paginator(paginator) @_paginator = paginator end def _model_class - @model ||= _model_name.to_s.safe_constantize + return @model if @model + @model = _model_name.to_s.safe_constantize + fail NameError, "model could not be found for #{self.name}" if @model.nil? + @model end def _allowed_filter?(filter) !_allowed_filters[filter].nil? end @@ -668,10 +671,19 @@ options = attrs.extract_options! options[:module_path] = module_path attrs.each do |attr| check_reserved_relationship_name(attr) + + # Initialize from an ActiveRecord model's properties + if _model_class < ActiveRecord::Base + model_association = _model_class.reflect_on_association(attr) + if model_association + options[:class_name] ||= model_association.class_name + end + end + @_relationships[attr] = relationship = klass.new(attr, options) associated_records_method_name = case relationship when JSONAPI::Relationship::ToOne then "record_for_#{attr}" when JSONAPI::Relationship::ToMany then "records_for_#{attr}" @@ -739,10 +751,10 @@ records = resource_klass.apply_filters(records, filters, options) end sort_criteria = options.fetch(:sort_criteria, {}) unless sort_criteria.nil? || sort_criteria.empty? - order_options = self.class.construct_order_options(sort_criteria) + order_options = relationship.resource_klass.construct_order_options(sort_criteria) records = resource_klass.apply_sort(records, order_options) end paginator = options[:paginator] if paginator