0

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.

Don Giulio
  • 2,946
  • 3
  • 43
  • 82
  • 2
    You question is not clear. Are you asking how to implement inheritance at database level in rails? Look for STI in Rails, there are lots of tutorials on it. – Rajesh Kolappakam Sep 16 '13 at 14:50
  • 1
    To get an idea of STI check out following links: http://therailworld.com/posts/18-Single-Table-Inheritance-with-Rails http://railscasts.com/episodes/394-sti-and-polymorphic-associations http://blog.thirst.co/post/14885390861/rails-single-table-inheritance – Matthias Sep 16 '13 at 14:56
  • Thank you, I don't need STI, I need quite the opposite, multiple database tables, that are accessed by models having the same code. At this stage I'm attempting DRY code, not DRY database. Thanks for the nice links anyhow. – Don Giulio Sep 16 '13 at 15:04

1 Answers1

2

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

Community
  • 1
  • 1
masahji
  • 544
  • 2
  • 6