Ruby Forum Rails deployment > Multiple tables using one model?

Posted by Lucas Campbell (lucasc)
on 26.02.2008 00:44
Is there a way to use one model to write to different tables if all of
the tables have the same fields and attributes?

I would like to use one model but be able to decide which table it
accesses.

Anyone know if this is possible?
Posted by Raul (Guest)
on 26.02.2008 01:00
(Received via mailing list)
Well, even if it were possible I wouldn't advise it. The point of the 
model
is to model your database, so each table you work with should have a 
model.
I would say you'd have two models but have the logic in your method to
determine which model to interact with.  Hope that helps a bit.

Raul



----- Original Message -----
From: "Lucas Campbell" <ruby-forum-incoming@andreas-s.net>
To: <rubyonrails-deployment@googlegroups.com>
Sent: Monday, February 25, 2008 3:44 PM
Subject: [Rails-deploy] Multiple tables using one model?
Posted by James Mccarthy (noagenda)
on 26.02.2008 01:02
(Received via mailing list)
class AbstractBase < ActiveRecord::Base
           self.abstract_class = true
end

class Foo < AbstractBase
     self.table_name = 'footable'
end

class Bar < AbstractBase
     self.table_name = 'bartable'
end

you may not need to set the table_name if the class names map to rails
conventions but just in case you need to do it that way.

Or;

module SharedStuff
  all your common code amongst the models
end

class Foo < ActiveRecord::Base
   include SharedStuff
end

class Bar < ActiveRecord::Base
   include SharedStuff
end

either should achieve the same end.

James McCarthy
james2mccarthy@gmail.com
Posted by Chris Williams (ceedub)
on 18.08.2008 22:10
James Mccarthy wrote:
> class AbstractBase < ActiveRecord::Base
>            self.abstract_class = true
> end
> 
> class Foo < AbstractBase
>      self.table_name = 'footable'
> end
> 
> class Bar < AbstractBase
>      self.table_name = 'bartable'
> end
> 
> you may not need to set the table_name if the class names map to rails
> conventions but just in case you need to do it that way.
> 

Generating a separate model for each works best and you won't need the 
self.table_name='x'. The logic and associations can still all be in the 
AbstractBase.