ruby-on-rails – 使用has_many的多个数据库连接

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用has_many的多个数据库连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何通过多个数据库连接来创建has_many?

我有一个名为“master”的数据库,用于保存位置信息.这是从单独的应用程序更新.用户可以访问许多位置,但所有其他模型都位于另一个名为“预算”的数据库中.以下是模型的设置方法.

# place.rb
class Place < ActiveRecord::Base
  belongs_to :user
  belongs_to :location
end

# user.rb
class User < ActiveRecord::Base
  has_many :locations,:through => :places
  has_many :places
end

# location.rb
class Location < ActiveRecord::Base
  establish_connection "master"
  has_many :places
  has_many :users,:through => :places
end

当我通过irb运行命令时,我得到以下内容

> Location.first.places.create(:user_id => 1)
> #<Place id: 1,user_id: 1,location_id: 1,created_at: "2011-11-28 20:58:43",updated_at: "2011-11-28 20:58:43">

> Location.first.places
> [#<Place id: 1,updated_at: "2011-11-28 20:58:43">]

> Location.first.users
> [#<User id: 1,username: "toby",role: "guest",created_at: "2011-11-28 17:45:40",updated_at: "2011-11-28 17:45:40">

> User.first.locations
> MysqL2::Error: Table 'master.places' doesn't exist: SELECT `locations`.* FROM `locations` INNER JOIN `places` ON `locations`.`id` = `places`.`location_id` WHERE `places`.`user_id` = 1 ActiveRecord::StatementInvalid: MysqL2::Error: Table 'master.places' doesn't exist: SELECT `locations`.* FROM `locations` INNER JOIN `places` ON `locations`.`id` = `places`.`location_id` WHERE `places`.`user_id` = 1

我尝试将当前rails env添加到Place以尝试覆盖场所的默认数据库,如下所示:
#place.rb
class Place<的ActiveRecord :: Base的
establish_connection Rails.env
belongs_to:用户
belongs_to:location
结束

#database.yml

master:
  adapter: MysqL2
  encoding: utf8
  reconnect: false
  database: master
  pool: 5
  username: root
  password:
  socket: /var/run/MysqLd/MysqLd.sock
development:
  adapter: MysqL2
  encoding: utf8
  reconnect: false
  database: budget_development
  pool: 5
  username: root
  password:
  socket: /var/run/MysqLd/MysqLd.sock

这没有用.有任何想法吗?

解决方法

一位朋友为我回答了这个问题,我认为这可能对其他人有用.
class Location < ActiveRecord::Base
  #establish_connection "master"
  def self.table_name() "master.locations" end
  has_many :places
  has_many :users,:through => :places
end
原文链接:https://www.f2er.com/ruby/268107.html

猜你在找的Ruby相关文章