mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 23:06:50 +00:00
Adding info to the readme on how to specify the type, adding an additional
test to cover a computed property without a type
This commit is contained in:
parent
25c564bd6f
commit
72652ce37e
14
README.md
14
README.md
@ -232,6 +232,20 @@ class PostSerializer < ActiveModel::Serializer
|
|||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The type of a computed attribute (like :full_name above) is not easily
|
||||||
|
calculated without some sophisticated static code analysis. To specify the
|
||||||
|
type of a computed attribute:
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
class PersonSerializer < ActiveModel::Serializer
|
||||||
|
attributes :first_name, :last_name, {:full_name => :string}
|
||||||
|
|
||||||
|
def full_name
|
||||||
|
"#{object.first_name} #{object.last_name}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
If you would like the key in the outputted JSON to be different from its name
|
If you would like the key in the outputted JSON to be different from its name
|
||||||
in ActiveRecord, you can use the `:key` option to customize it:
|
in ActiveRecord, you can use the `:key` option to customize it:
|
||||||
|
|
||||||
|
|||||||
@ -491,16 +491,17 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
|
|
||||||
# Computed attributes (not real columns or associations).
|
# Computed attributes (not real columns or associations).
|
||||||
def can_edit; end
|
def can_edit; end
|
||||||
|
def can_view; end
|
||||||
def drafts; end
|
def drafts; end
|
||||||
|
|
||||||
attributes :name, :age, :can_edit => :boolean
|
attributes :name, :age, {:can_edit => :boolean}, :can_view
|
||||||
has_many :posts, :serializer => Class.new
|
has_many :posts, :serializer => Class.new
|
||||||
has_many :drafts, :serializer => Class.new
|
has_many :drafts, :serializer => Class.new
|
||||||
has_one :parent, :serializer => Class.new
|
has_one :parent, :serializer => Class.new
|
||||||
end
|
end
|
||||||
|
|
||||||
assert_equal serializer.schema, {
|
assert_equal serializer.schema, {
|
||||||
:attributes => { :name => :string, :age => :integer, :can_edit => :boolean },
|
:attributes => { :name => :string, :age => :integer, :can_edit => :boolean, :can_view => nil },
|
||||||
:associations => {
|
:associations => {
|
||||||
:posts => { :has_many => :posts },
|
:posts => { :has_many => :posts },
|
||||||
:drafts => nil,
|
:drafts => nil,
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user