to_xml Doesn't Work on Objects Returned Through Rails ActiveRecord habtm Reference

后端 未结 1 1831
轻奢々
轻奢々 2021-01-14 18:27

I have two rails active record classes, School and Instructor linked by a has_and_belongs_to_many relationship.

I need to query my instructors_controller for instruc

1条回答
  •  隐瞒了意图╮
    2021-01-14 19:01

    to_xml() tries to define a type attribute for each model attribute. For example, a User model with an age (INT) attribute will have: 42. This type information is not encoded in JSON, which is why to_json() works for you. Add this method to your Instructor model:

    def to_xml(options = {})
      to_xml_opts = {:skip_types => true} # no type information, not such a great idea!
      to_xml_opts.merge!(options.slice(:builder, :skip_instruct))
      # a builder instance is provided when to_xml is called on a collection of instructors,
      # in which case you would not want to have  added to each item
      to_xml_opts[:root] ||= "instructor"
      self.attributes.to_xml(to_xml_opts)
    end
    

    This would however make your XML devoid of any type information - not good if someone has a JAVA REST client. A better strategy would be to filter self.attributes.slice(*keys).to_xml(to_xml_opts) where keys is an array of model attributes you want in the XML.

    0 讨论(0)
提交回复
热议问题