2

should a non-database data class I need be created as a Rails 3 "model", or just a basic class in the /lib area?

I want to build some classes to represent calculated domain objects. So the fields won't reference a database table/column. There will be also methods in the class that with the data.

Question - When generating these classes should these be just normal Ruby classes I put in the /lib area? Or should I/can I use rails models for this (and generate with "rails g model ...")?

Greg
  • 34,042
  • 79
  • 253
  • 454

3 Answers3

2

Tableless models should probably be kept in app/models. I have several that access APIs. ActiveModel in Rails can help bring in some of the useful functionality of Active Record.

ScottJShea
  • 7,041
  • 11
  • 44
  • 67
1

Interesting question..I had the same question a few weeks back.

I put those class under model directory. This is how I came up with that decision. The class that I wrote was completely related to a particular app no common features to share with anyone at-least at the moment. I also needed to use some of my existing models to query some data in that class. So I made it a class under model directory. I might be wrong but thats what I have done now.

In another case where I am using a certain api sets for a web and mobile app I am thinking of making the code which interfaces with the api into a gem. The thing to note here is that the api set is also part my system and it will only be used by my apps.

Josnidhin
  • 12,469
  • 9
  • 42
  • 61
1

Classes that don't map to database tables can still reside inside of app/models. Instead of extending your class from ActiveRecord::Base, you can simply declare your class without any extensions (or your own extensions).

The CanCan ability model is a good example of this. It resides in app/models/, however does not extend ActiveRecord::Base. More information on CanCan's ability model can be found here: https://github.com/ryanb/cancan/wiki/Defining-Abilities

Also consider that code under lib/ will not reload in the development environment by default.

Ben Simpson
  • 4,009
  • 1
  • 18
  • 10