Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Examples of using relationships during create / update #144

Open
garytaylor opened this issue Nov 17, 2015 · 4 comments
Open

Examples of using relationships during create / update #144

garytaylor opened this issue Nov 17, 2015 · 4 comments

Comments

@garytaylor
Copy link
Contributor

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

@rondale-sc
Copy link

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

@rondale-sc
Copy link

@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

@JohnSmall
Copy link

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?

@masimons
Copy link

@JohnSmall does it work if you do something like Resource.find('the resource id').includes(:authors).first?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants