jondavidjohn
jondavidjohn

Reputation: 62392

Rails to_xml vs as_json

Trying to mirror my API responses with as little code duplication as possible and have this so far....

Really, this is a "There has to be a better 'Rails way' to accomplish this..." question.

class Quote < ActiveRecord::Base
    belongs_to :author
    has_many :votes

    def as_json(options={})
        hash = super(except)
        hash[:author] = self.author.name
        hash[:vote_count] = self.votes.count
        hash
    end

    def to_xml(options={})
        hash = super(except)
        hash[:author] = self.author.name // <---- line 14
        hash[:vote_count] = self.votes.count
        hash
    end

    private

    def except
        { :except => [ :id, :created_at, :updated_at, :author_id ] }
    end

end

JSON response works like a champ, but the xml throws this error

can't convert Symbol into Integer

app/models/quote.rb:14:in `[]='
app/models/quote.rb:14:in `to_xml'

As a secondary question, is the the best way to customize the output like I am? I'd like to not duplicate this logic if I can avoid it.

    hash[:author] = self.author.name
    hash[:vote_count] = self.votes.count
    hash

Upvotes: 0

Views: 328

Answers (1)

Matchu
Matchu

Reputation: 85784

to_xml returns an XML string, not a hash. That's why it's surprised by a symbol in the brackets: it thinks you're trying to modify a particular character, e.g. name[0] = 'A'

If you're interested in changing bits of the XML output, maybe you should just build a new hash of the attributes you want and run to_xml on that.

Upvotes: 2

Related Questions