flobacca
flobacca

Reputation: 978

Rails, rendering to_xml not showing model's fields

I have a Song model which I want to display in xml format.

My controller is

class SongsController < ApplicationController
  def index
    @songs = Song.all
    respond_to do |format|
      format.html
      format.xml {render :xml =>  @songs.to_xml}
    end
  end
end

My results are

<songs type="array">
<song type="Song">#<Song:0x00007f8ce441b810></song>
<song type="Song">#<Song:0x00007f8ce441b428></song>
</songs>

I would like the fields inside the songs to be shown, like this.

<songs type="array">
  <song>
    <filename>take_to_the_sky_loveshadow</filename>
    <id type="integer">19</id>
    <link-to-new-work-license>http://creativecommons.org/licenses/by/3.0/</link-to-new-work-license>
  ...

It looks to me like the Song addresses are showing and I'm not sure why. I have looked at many Stackoverflow questions about formatting for xml, but none seem to have this 'addresses' result.

Thank you for your help.

Upvotes: 1

Views: 122

Answers (1)

Stanislav Zaleski
Stanislav Zaleski

Reputation: 414

I managed to solve this problem in two ways:

1) Add gem 'activemodel-serializers-xml' into Gemfile. After that @songs.to_xml will work as expected (it will serialize all model fields)

2) If you don't want to install this gem, you can do @songs.map(&:as_json).to_xml

The first way seems to be a better solution

Upvotes: 2

Related Questions