5

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?

nc.
  • 105
  • 3
  • 7
  • http://stackoverflow.com/questions/993839/how-to-iterate-activerecord-attributes-including-attr-accessor-methods – Brad Werth Sep 19 '13 at 22:52

4 Answers4

3

Just don't inherit from ActiveRecord::Base

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

J Cooper
  • 16,891
  • 12
  • 65
  • 110
  • Is it not possible to mix and match? – nc. Dec 30 '08 at 03:54
  • 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 Dec 30 '08 at 03:59
  • So you have some table attributes exposed automatically, and some defined purely by methods? – nc. Dec 30 '08 at 03:59
  • 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. Dec 30 '08 at 04:00
  • 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. Dec 30 '08 at 04:03
3

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.

Adam Tanner
  • 917
  • 6
  • 9
1

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
  • 14,295
  • 2
  • 36
  • 26
1

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 Knight
  • 8,346
  • 4
  • 33
  • 32