@@ -6,12 +6,12 @@ class Relationship
6
6
# {http://jsonapi.org/format/#document-links Document Links}
7
7
# {http://jsonapi.org/format/#document-resource-object-linkage Document Resource Relationship Linkage}
8
8
# {http://jsonapi.org/format/#document-meta Docment Meta}
9
- def initialize ( parent_serializer , serializer , serializable_resource_options , args = { } )
9
+ def initialize ( parent_serializer , association , serializable_resource_options , args = { } )
10
10
@object = parent_serializer . object
11
11
@scope = parent_serializer . scope
12
12
@association_options = args . fetch ( :options , { } )
13
13
@serializable_resource_options = serializable_resource_options
14
- @data = data_for ( serializer )
14
+ @data = data_for ( association )
15
15
@links = args . fetch ( :links , { } ) . each_with_object ( { } ) do |( key , value ) , hash |
16
16
result = Link . new ( parent_serializer , value ) . as_json
17
17
hash [ key ] = result if result
@@ -38,13 +38,23 @@ def as_json
38
38
39
39
private
40
40
41
- def data_for ( serializer )
42
- if serializer . respond_to? ( :each )
41
+ def data_for ( association )
42
+ if association . to_many?
43
+ serializer = association . serializer
43
44
serializer . map { |s | ResourceIdentifier . new ( s , serializable_resource_options ) . as_json }
44
45
elsif association_options [ :virtual_value ]
45
46
association_options [ :virtual_value ]
46
- elsif serializer && serializer . object
47
- ResourceIdentifier . new ( serializer , serializable_resource_options ) . as_json
47
+ elsif association . belongs_to?
48
+ foreign_key = association . reflection . foreign_key
49
+ if @object . respond_to? ( foreign_key )
50
+ {
51
+ id : @object . send ( foreign_key ) ,
52
+ type : association . reflection . type . to_s
53
+ }
54
+ else
55
+ serializer && serializer . object &&
56
+ ResourceIdentifier . new ( serializer , serializable_resource_options ) . as_json
57
+ end
48
58
end
49
59
end
50
60
end
0 commit comments