Rails 4 - Mapping a model dynamically on two different database tables -
i have multi domain app talking legacy database. in db have 2 tables different names, lets call them user_a
, user_b
. structure , data types same, difference data different domains.
now, have single scaffold (model/controller/view)
that, depending on domain, maps right db table.
domain work model/controller called user
maps internally db table user_a
, , domain b work same model/controller user
maps table user_b
.
i use resource :user
in routes access model rails way.
so somehow need overwrite model on initialization not quite sure how go it.
how 1 go using rails activerecord?
i don't have multitable db ready test with, educated guess @ solution:
# respective models class user < activerecord::base end class domainauser < user self.table_name = "user_a" end class domainbuser < user self.table_name = "user_b" end # controller def set_user @user = if request.subdomain(0) == "domaina" domainauser.find(params[:id]) else domainbuser.find(params[:id]) end end
edit: here's alternative bit of metaprogramming hackery subclass instantization within parent class itself. tested , working.
i wouldn't want maintain though.
# model class user < activerecord::base def self.for_domain(domain_suffix) class_eval "class domainuser < user; self.table_name='user_#{domain_suffix}'; end" "user::domainuser".constantize end end # controller user.for_domain("a").new
Comments
Post a Comment