edoloughlin
edoloughlin

Reputation: 5891

Rails 3 ActiveModel::Serializers seem to need lots of support methods

I'm returning to RoR after not using it for a few years and I'm trying to use ActiveModel to serialise a plain object to XML.

I'm doing the following, as per the comments in activemodel/lib/activemodel/serialization.rb:

class XmlError

  include ActiveModel::Serializers::Xml

  attr_accessor :code
  attr_accessor :description

  def attributes
    @attributes ||= {'code' => 'nil', 'description' => 'nil'}
  end

  def initialize(error_code)
    @code = error_code
    @description = "blah"
   self
  end
end

I use this in a controller as:

render :xml => XmlError.new("invalid_login")

and I get the following stacktrace:

NoMethodError (undefined method `model_name' for XmlError:Class):

app/controllers/users_controller.rb:19:in `login'

app/controllers/users_controller.rb:5:in `login'

If create a model_name class method, I then get the following stacktrace:

NoMethodError (undefined method `element' for "XmlError":String):

app/controllers/users_controller.rb:19:in `login'

app/controllers/users_controller.rb:5:in `login'

It feels like I'm chasing my tail here. Have I just missed something simple in my class? I followed the example closely.

Upvotes: 0

Views: 793

Answers (2)

Joe Van Dyk
Joe Van Dyk

Reputation: 6940

extend ActiveModel::Naming

is what you are looking for.

http://rdoc.info/github/lifo/docrails/master/ActiveModel/Naming

Upvotes: 2

drummondj
drummondj

Reputation: 1483

Why not sub-class ActiveModel::Base?

Upvotes: 0

Related Questions