Skip to content

Commit b65f191

Browse files
committed
Add examples to README.md.
1 parent 5437114 commit b65f191

File tree

1 file changed

+72
-1
lines changed

1 file changed

+72
-1
lines changed

Diff for: README.md

+72-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,78 @@ $ gem install jsonapi-rails
2323

2424
## Usage
2525

26-
TODO
26+
### Serialization
27+
28+
Example:
29+
```ruby
30+
# app/serializable/serializable_user.rb
31+
class SerializableUser < JSONAPI::Serializable::Model
32+
type 'users'
33+
34+
attribute :name
35+
attribute :email do
36+
"#{@model.name}@foo.bar"
37+
end
38+
39+
has_many :posts do
40+
# data is auto-inferred
41+
link(:related) { @url_helpers.user_posts(@model) }
42+
meta foo: :bar
43+
end
44+
45+
has_many :comments do
46+
data do
47+
@user.comments.order(:desc)
48+
end
49+
end
50+
51+
has_many :reviews, Foo::Bar::SerializableRev
52+
53+
link(:self) { @url_helpers.user_url(@model.id) }
54+
meta do
55+
{ foo: 'bar' }
56+
end
57+
end
58+
59+
# app/controllers/users_controller.rb
60+
# ...
61+
user = User.find_by(id: id)
62+
render jsonapi: user, include: { posts: [:comments] }, meta: { foo: 'bar' }
63+
# ...
64+
```
65+
66+
### Deserialization
67+
68+
Example:
69+
```ruby
70+
class PostsController < ActionController::Base
71+
deserializable_resource :post, only: [:create, :update] do
72+
attribute :title
73+
attribute :date
74+
has_one :author do |rel, id, type|
75+
field user_id: id
76+
field user_type: type
77+
end
78+
has_many :comments
79+
end
80+
81+
def create_params
82+
params.require(:user).permit!
83+
end
84+
85+
def create
86+
create_params[:title]
87+
create_params[:date]
88+
create_params[:comment_ids]
89+
create_params[:comment_types]
90+
create_params[:user_id]
91+
create_params[:user_type]
92+
# ...
93+
end
94+
end
95+
96+
97+
```
2798

2899
## License
29100

0 commit comments

Comments
 (0)