Merge pull request #117 from joliss/computed-attributes

Make schema not crash on computed attributes & associations
This commit is contained in:
Jo Liss 2012-11-22 08:31:18 -08:00
commit 2fc083a1fe
2 changed files with 41 additions and 20 deletions

View File

@ -169,16 +169,31 @@ module ActiveModel
klass = model_class klass = model_class
columns = klass.columns_hash columns = klass.columns_hash
attrs = _attributes.inject({}) do |hash, (name,key)| attrs = {}
column = columns[name.to_s] _attributes.each do |name, key|
hash.merge key => column.type if column = columns[name.to_s]
attrs[key] = column.type
else
# Computed attribute (method on serializer or model). We cannot
# infer the type, so we put nil.
attrs[key] = nil
end
end end
associations = _associations.inject({}) do |hash, (attr,association_class)| associations = {}
_associations.each do |attr, association_class|
association = association_class.new(attr, self) association = association_class.new(attr, self)
model_association = klass.reflect_on_association(association.name) if model_association = klass.reflect_on_association(association.name)
hash.merge association.key => { model_association.macro => model_association.name } # Real association.
associations[association.key] = { model_association.macro => model_association.name }
else
# Computed association. We could infer has_many vs. has_one from
# the association class, but that would make it different from
# real associations, which read has_one vs. belongs_to from the
# model.
associations[association.key] = nil
end
end end
{ :attributes => attrs, :associations => associations } { :attributes => attrs, :associations => associations }

View File

@ -489,15 +489,21 @@ class SerializerTest < ActiveModel::TestCase
define_method(:model_class) do model end define_method(:model_class) do model end
end end
attributes :name, :age # Computed attributes (not real columns or associations).
def can_edit; end
def drafts; end
attributes :name, :age, :can_edit
has_many :posts, :serializer => Class.new has_many :posts, :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 }, :attributes => { :name => :string, :age => :integer, :can_edit => nil },
:associations => { :associations => {
:posts => { :has_many => :posts }, :posts => { :has_many => :posts },
:drafts => nil,
:parent => { :belongs_to => :parent } :parent => { :belongs_to => :parent }
} }
} }