Question

I have some rails models which don't need any persistence, however I'd like rails to think the model actually has attributes x, y, z so when calling methods like to_json in the controller I get them included for free.

For example,

class ModelWithoutTableColumns << ActiveRecord::Base

def x
   return "Custom stuff here"
end

There is no column x in the database for Table "ModelWithoutTable" (sorry for the slightly confusing name!)

Anyone have an idea how to tackle this one?

Was it helpful?

Solution

Sounds like you want ActiveModel. Check out http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ for a great walkthrough by Yehuda Katz. Specifically the section called "Serialization" for your to_json requirements.

OTHER TIPS

Just don't inherit from ActiveRecord::Base

Edit: Have you tried passing options to to_json, like :methods perhaps? See here

That won't work--ActiveRecord::Base defines to_json, but requires a table.

You should check out the ActiveRecord::BaseWithoutTable plugin. Here's how to use it, and here's an updated version for Rails 2.

I haven't tried either of them, so no guarantees.

You might also want to check out acts_without_database, the current details about it are here, but the site is down at the moment. Here's the posting on RubyFlow, it's from today.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top