在rails中的单个模型文件中映射两个数据库表

时间:2013-09-17 10:32:30

标签: ruby-on-rails model

我有两个表users和user_new。这两个表都具有相同的模式:

id INT
name VARCHAR(20)
email address  VARCHAR(20)
age  INT
address  VARCHAR(20)

我想将这两个表映射到Rails模型文件中的单个模型文件User。

任何人都可以建议我在Rails中执行此活动的好方法。如果需要澄清,请告诉我?

2 个答案:

答案 0 :(得分:0)

最好的解决方案是将架构更改为STI(单表继承)。向用户添加“类型”列,您可以创建不同的用户。使用STI,您始终可以与一个用户对象进行交互,而不是与一个奇怪的关联。要了解STI,请查看以下链接:

1- http://www.therailworld.com/posts/18-Single-Table-Inheritance-with-Rails

2- http://www.railscasts.com/episodes/394-sti-and-polymorphic-associations

3- http://blog.thirst.co/post/14885390861/rails-single-table-inheritance

Mattherick在上述一个问题上的原始答案。

4- A Free screencast from TeachMeToCode

例如:

# /app/models/sports/sport.rb
class Sport < ActiveRecord::Base
  # Methods, variables and constants
end


# /app/models/sports/probasketball.rb
class ProBasketball < Sport
  # Methods, variables and constants
end


# /app/models/sports/profootball.rb
class ProFootball < Sport
  # Methods, variables and constants
end



# /app/models/sports/baseball.rb
class Baseball < Sport
  # Methods, variables and constants
end

答案 1 :(得分:-1)

您可以使用以下代码在user_new中创建新文件app/models

class UserNew < ActiveRecord::Base
  self.abstract_class = true
  establish_connection 'other_database'
  set_table_name "user_new"
end

加入database.yml

other_database:
  adapter: mysql2
  database: pudra
  username: root
  encoding: utf8
# use your connection params

现在你有两个模型,连接到不同的数据库。那么你可以:

UserNew.all.each do |user_new|
  User.create(name: user_new.name, email: user_new.email, age: user_new.age)
end

如果这些表在一​​个数据库中,你只能:

class UserNew < ActiveRecord::Base
  set_table_name "user_new"
end