Make schema not crash on computed attributes

We do not know the type for computed attributes, so we pick nil.

Perhaps at some point we might add a :type option for attributes (or
not), but in any case it's important to not crash when there are
computed attributes.
This commit is contained in:
Jo Liss 2012-08-17 21:52:00 +02:00
parent 9f5e1b1776
commit 6281a9149e
2 changed files with 26 additions and 17 deletions

View File

@ -169,9 +169,15 @@ 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.inject({}) do |hash, (attr,association_class)|

View File

@ -678,13 +678,16 @@ class SerializerTest < ActiveModel::TestCase
define_method(:model_class) do model end define_method(:model_class) do model end
end end
attributes :name, :age # Computed attribute; not a column.
def can_edit; end
attributes :name, :age, :can_edit
has_many :posts, :serializer => Class.new has_many :posts, :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 },
:parent => { :belongs_to => :parent } :parent => { :belongs_to => :parent }