Reputation: 3284
In my project I have two models which have identical attributes, methods and everything the same.
at the moment they are in app/models/ in separate rb files, with quite some repetition of code.
I would like to export all that code to a separate file and have the two files referring to it, and have mode DRY code.
I've tried the following, but it didn't work:
# app/models/order.rb
class Order < ActiveRecord::Base
before_save { self.version += 1 }
attr_accessible :order
attr_accessible :filled_date
validates :order, :presence => true
end
and one of the referring orders is:
# app/models/real_order.rb
class RealOrder < Order
belongs_to :User, inverse_of: :real_orders
end
but this doesn't work, and I get a Could not find table 'orders'
when I try to use the models.
Also I'm thinking that Orders
is not a real model, so probably the app/models
is not really the right place for that file, though I'm not sure in what directory it should be.
thanks,
UPD1: The structure I would like to achieve in the end is a situation where I have two identical database tables, with two separate models that are based on the same code. I would like to write such code only once in a separate superclass file. So I'm looking for DRY code, not DRY database.
Upvotes: 0
Views: 410
Reputation: 544
There are a few different ways to share code between models. If it makes sense (for your problem domain) to use inheritance (as in your example above), then you need the following in your Order
class:
self.abstract_class = true
You can also use mixins.
Here's a good question about this: ruby inheritance vs mixins
Upvotes: 2