Format xml with properties with acts_as_api

2019-09-04 19:13发布

问题:

i have a doubt with acts_as_api. i want to format a xml string like this:

<root>
  <child property="property_value">Some Text</child>
  etc
</root>

this is possible?

thank's in advance

回答1:

I think this will not work automagically as you want to put data in your XML structure in two different places:

  • The properties of the nodes
  • The content of the nodes

But the attributes of your model are contained a single Hash. acts_as_api (or another serializer) can't determine which attributes are supposed to be in a property and which one should be taken as the inner text.

For this case you will have to provide your own serializer (you can have a look at http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#method-i-to_xml on how to do it in Rails.



回答2:

the intended use of acts_as_api is to go with key value pairs.

if you want to break that convention by mixing content and structure, you are probably better of creating your own xml without using the library support in the first place.

what you could do, i don't think that it's a good idea though, is to place the result of one call to acts_as_api into the value of your root tag.

you might be able to re-use the acts_as_api behaviour of the child model.