mirror of https://github.com/rails/rails
Add support for overriding associations, mostly used for authorization
This commit is contained in:
parent
776da539d7
commit
22c322f056
|
@ -41,6 +41,10 @@ module ActiveModel
|
|||
def associate(klass, attrs)
|
||||
options = attrs.extract_options!
|
||||
self._associations += attrs.map do |attr|
|
||||
unless method_defined?(attr)
|
||||
class_eval "def #{attr}() object.#{attr} end", __FILE__, __LINE__
|
||||
end
|
||||
|
||||
options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer")
|
||||
klass.new(attr, options)
|
||||
end
|
||||
|
@ -79,7 +83,7 @@ module ActiveModel
|
|||
hash = attributes
|
||||
|
||||
_associations.each do |association|
|
||||
associated_object = object.send(association.name)
|
||||
associated_object = send(association.name)
|
||||
hash[association.name] = association.serialize(associated_object, scope)
|
||||
end
|
||||
|
||||
|
|
|
@ -174,4 +174,30 @@ class SerializerTest < ActiveModel::TestCase
|
|||
}
|
||||
}, json)
|
||||
end
|
||||
|
||||
def test_overridden_associations
|
||||
author_serializer = Class.new(ActiveModel::Serializer) do
|
||||
attributes :first_name
|
||||
end
|
||||
|
||||
blog_serializer = Class.new(ActiveModel::Serializer) do
|
||||
const_set(:PersonSerializer, author_serializer)
|
||||
has_one :person
|
||||
|
||||
def person
|
||||
object.author
|
||||
end
|
||||
end
|
||||
|
||||
user = User.new
|
||||
blog = Blog.new
|
||||
blog.author = user
|
||||
|
||||
json = blog_serializer.new(blog, user).as_json
|
||||
assert_equal({
|
||||
:person => {
|
||||
:first_name => "Jose"
|
||||
}
|
||||
}, json)
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue