Allow relationship links to be declared as object method (#2)
* Allow relationship links to be declared as object method * Relationship links note added to readme
This commit is contained in:
parent
f04abfd2fe
commit
83e99b2923
@ -278,6 +278,12 @@ class MovieSerializer
|
||||
end
|
||||
```
|
||||
|
||||
Relationship links can also be configured to be defined as a method on the object.
|
||||
|
||||
```ruby
|
||||
has_many :actors, links: :actor_relationship_links
|
||||
```
|
||||
|
||||
This will create a `self` reference for the relationship, and a `related` link for loading the actors relationship later. NB: This will not automatically disable loading the data in the relationship, you'll need to do that using the `lazy_load_data` option:
|
||||
|
||||
```ruby
|
||||
|
@ -104,8 +104,12 @@ module FastJsonapi
|
||||
end
|
||||
|
||||
def add_links_hash(record, params, output_hash)
|
||||
output_hash[key][:links] = links.each_with_object({}) do |(key, method), hash|
|
||||
Link.new(key: key, method: method).serialize(record, params, hash)\
|
||||
if links.is_a?(Symbol)
|
||||
output_hash[key][:links] = record.public_send(links)
|
||||
else
|
||||
output_hash[key][:links] = links.each_with_object({}) do |(key, method), hash|
|
||||
Link.new(key: key, method: method).serialize(record, params, hash)\
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -67,5 +67,28 @@ describe FastJsonapi::ObjectSerializer do
|
||||
expect(actor_hash).not_to have_key(:data)
|
||||
end
|
||||
end
|
||||
|
||||
context "relationship links defined by a method on the object" do
|
||||
before(:context) do
|
||||
class Movie
|
||||
def relationship_links
|
||||
{ self: "http://movies.com/#{id}/relationships/actors" }
|
||||
end
|
||||
end
|
||||
|
||||
class LinksPassingMovieSerializer < MovieSerializer
|
||||
has_many :actors, links: :relationship_links
|
||||
end
|
||||
end
|
||||
|
||||
let(:serializer) { LinksPassingMovieSerializer.new(movie) }
|
||||
let(:links) { hash[:data][:relationships][:actors][:links] }
|
||||
let(:relationship_url) { "http://movies.com/#{movie.id}/relationships/actors" }
|
||||
|
||||
it "generates relationship links in the object" do
|
||||
expect(links).to be_present
|
||||
expect(links[:self]).to eq(relationship_url)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
Loading…
x
Reference in New Issue
Block a user