knt
knt

Reputation: 7603

Rails 3.0 Models in two different db's causing table does not exist error in view

In my Rails 3.0 app, I have two models, Concepts and Categories. Concepts have a category_id field that maps to a category. For various reasons, these models have to be stored in two different databases, both different from my main app db:

class Concept < ActiveRecord::Base
  establish_connection configurations[Rails.env]["db1"]
  set_table_name "concepts"
end

class Category < ActiveRecord::Base
  establish_connection configurations[Rails.env]["db2"]
  set_table_name "categories"
end

To get a concept's category, I have a method in my concept model like so:

In app/models/concept.rb:

  def category
    Category.find_by_id(category_id)
  end

In ther rails console, this works without any problems. However, if I try to do @concept.category on the concept show page, I get this error:

Table 'myapp_development.categories' doesn't exist

Any idea what's causing this?

Upvotes: 0

Views: 333

Answers (1)

Krule
Krule

Reputation: 6476

Interesting problem. Never tried this before.

You don't need set_table_name if model name is singular of tabel name, like yours is.

If you set your database connections in database.yml, like you would normally do, pass connection names as shown bellow.

You did forget to add associations do and that is why you are getting an exception.

Just tested it with:

# config/database.yml
db1:
  adapter: mysql2
  database: db1
  username: username
  password: password

db2:
  adapter: mysql2
  database: db2
  username: some_other_username
  password: some_other_password

# models/concept.rb
class Concept < ActiveRecord::Base
  establish_connection :db1
  belongs_to :category
end

# models/category.rb
class Category < ActiveRecord::Base
  establish_connection :db2
  has_one :concept
end

It behaves as if it is a single database.

Upvotes: 1

Related Questions