Multiple tables using one model?

23 views
Skip to first unread message

Lucas Campbell

unread,
Feb 25, 2008, 6:44:14 PM2/25/08
to rubyonrails...@googlegroups.com
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 via http://www.ruby-forum.com/.

Raul

unread,
Feb 25, 2008, 6:59:53 PM2/25/08
to rubyonrails...@googlegroups.com
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

James McCarthy

unread,
Feb 25, 2008, 7:01:34 PM2/25/08
to rubyonrails...@googlegroups.com
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
james2m...@gmail.com

Chris Williams

unread,
Aug 18, 2008, 4:10:55 PM8/18/08
to rubyonrails...@googlegroups.com
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.

Reply all
Reply to author
Forward
0 new messages