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
columns = klass.columns_hash
attrs = _attributes.inject({}) do |hash, (name,key)|
column = columns[name.to_s]
hash.merge key => column.type
attrs = {}
_attributes.each do |name, key|
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
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
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_one :parent, :serializer => Class.new
end
assert_equal serializer.schema, {
:attributes => { :name => :string, :age => :integer },
:attributes => { :name => :string, :age => :integer, :can_edit => nil },
:associations => {
:posts => { :has_many => :posts },
:parent => { :belongs_to => :parent }