views:

1953

answers:

3

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?

+2  A: 

Just don't inherit from ActiveRecord::Base

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

J Cooper
Is it not possible to mix and match?
nc
Well, you can obviously define whatever custom methods/attributes you want in any model -- they are just Ruby classes, after all. I inferred from your model name that you didn't want it to be DB-backed whatsoever :)
J Cooper
So you have some table attributes exposed automatically, and some defined purely by methods?
nc
Thing is I've tried that and rails builtins like to_json don't recognize those methods (attr_accessor :x) as being part of the model 'table' attributes. Feels very un-intuitive, I think I am missing something obvious.
nc
It seems like Rails is discriminating table attributes vs Ruby attributes . I was wondering if there is a Rails way of defining a Ruby attribute to be a 'proper' one?!
nc
+1  A: 

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.

zenazn
+1  A: 

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.

Tim K.