简体   繁体   English

Rails 3,多个数据库连接和设置模型

[英]rails 3, multiple database connections and setting up models

When working with multiple database connections and setting up models to work with those different instances, how do you setup the has_many, has_one, belongs_to, etc? 当使用多个数据库连接并设置模型以使用那些不同的实例时,如何设置has_many,has_one,belongs_to等?

For example: 例如:

I have one database that is Read + Write, the other DB instance is used in my Rails app as Read only. 我有一个数据库为Read + Write,另一个数据库实例在我的Rails应用程序中用作只读。 The DB table that is Read only I am pulling back a list of Media items (Videos, Images and Audios). 只读的数据库表我正在拉回媒体项目(视频,图像和音频)的列表。 In my Read + Write DB I have a media_ratings table. 在我的读写数据库中,我有一个media_ratings表。

I have a model called AvMedia (The Read only DB) and a MediaRating Model (Read + Write DB). 我有一个称为AvMedia(只读数据库)的模型和一个MediaRating模型(读+写数据库)。 How do I setup The AvMedia model like so: has_one rating and setup the MediaRating model like so: has_many AvMedia? 如何设置类似avMedia的模型:has_one评级并设置类似MediaRating的模型:has_many AvMedia?

Sorry if this is confusing... I tried to explain it the best I could. 抱歉,这令人困惑...我尽力解释了一下。

In the AvMedia model you must include has_one :rating and just make sure that in the corresponding table you have a rating_id foreign key. 在AvMedia模型中,您必须包括has_one :rating并只需确保在相应的表中具有rating_id外键即可。 You also need belongs_to :avmedia in your rating model. 您还需要在评级模型中使用belongs_to :avmedia

A lot of magic goes on behind the scenes to automatically link your tables together when you define a relationship. 在定义关系时,幕后发生了很多魔术,可将表自动链接在一起。

It sounds like you don't need the has_many for AvMedia - from what you said it appears that it's a 1-1 relationship (one AvMedia has one rating, one rating corresponds with one AvMedia). 听起来您不需要AvMedia的has_many从您所说的看来,这是1-1的关系(一个AvMedia有一个等级,一个等级与一个AvMedia对应)。 If this is incorrect, let me know. 如果不正确,请通知我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM