Reputation: 1982
I am currently playing with rails, and I am trying to render my models to xml and json.
Now, in all my models I want to remove the created_at and updated_at columns - and adding an except to every single one of my to_xml/json is against DRY.
so I am wondering how can I do that.
I saw people overriding to_xml method - but i still have to do that to every model - and what if there is this one place i will need those columns?
I am looking for something like
xxx = :except => [:created_at, :updated_at]
and in each rendering I send xxx to the options.
Upvotes: 1
Views: 556
Reputation: 1982
I ended up creating a module overriding serializable_hash (for json and xml)
module DefaultRenderingModule
def serializable_hash (options = {})
if(options.has_key? :all)
super(options.except!(:all))
else
x = [:created_at, :updated_at]
if options.has_key? :except
x.append(options[:except])
end
options.merge! :except => x
super(options)
end
end
end
and I include it in every model i want this behavior
Upvotes: 2
Reputation: 18070
Override as_json in your model. This is what is used to generate the json when you do a
render :json => @object
def as_json(options = {})
super(options.merge(:except => [:created_at, :updated_at]))
end
You can play around with this - use the options submitted or not.
Use :only, :methods, and :include to completely customize the output.
Upvotes: 0
Reputation: 1219
Check docs http://apidock.com/rails/ActiveRecord/Serialization/to_json:
xxx.to_json(:except => [ :id, :created_at, :age ])
Upvotes: 0
Reputation: 1665
Have a look at https://github.com/rails-api/active_model_serializers for me that's the way
Upvotes: 0