Examples of using relationships during create / update
Whilst the relationships work find and are well documented for reading - I am finding that I really do not know what I am doing when trying to use them during creation / updating of a resource. I was expecting this to work :-
forum = Forum.find(1).first
forum.posts << Post.find(5)
forum.save
This is assuming that a forum has many posts
Please can you add some examples to the readme to explain how things like this should be done ? I am assuming now that it has something to do with the "relationships" method but can't be sure.
Thanks
Gary
I'm also curious about this. I'm currently giving
{
:title=>"Ember.js 1.11 Workshop",
:url=>"https://www.youtube.com/watch?v=8GMeMM0ukYM",
:relationships=>{:author=>{:data=>[{:type=>"people", :id=>"39"}]}}}
And was assuming that it'd be parse on init of my JsonApiClient::Resurce for saving. But haven't had any luck.
Any helper here would be greatly appreciated.
Cheers, Jon
@garytaylor There are some examples of this in the tests:
https://github.com/chingor13/json_api_client/blob/f779c3c6b4f8b292824238a92446d3cfa922fbe2/test/unit/updating_test.rb#L172
I believe given
class Resource < Base
has_many :authors
end
class Author < Base
end
You should be able to do:
author1 = Author.new(name: 'foo')
author1.save
author2 = Author.new(name: 'bar')
author2.save
r = Resource.new(title: 'foo')
r.relationships.authors = [author1, author2]
r.save
I can see how to save things in relationships, and it works, but I can't get them back again.
Taking the above example. If I were to do
r = Resource.find('the resource id').first
r.relationships.authors
Doesn't return the authors that were added, just the path to the relationships. So how do I find the authors related to the resource?
@JohnSmall does it work if you do something like Resource.find('the resource id').includes(:authors).first?