2

I'm building a webapp that has its own database called 'products_db'. But my app will have to call reviews which is located in the database 'reviews_db', which is a legacy db being used by another system that I can't do anything because client wants it that way.

So, luckily both db are located in the same SQL Server (MSSQL). I've already have te 'activerecord-sqlserver-adapter' working but I need to figure out a way to access 'reviews_db' from my webapp.

The reviews_db doesn't follow any Rails convention because its a legacy system.

So, my class Product:

class Product < ActiveRecord::Base
  attr_accessible :name, :description, :price

  has_many :reviews

end

And my class Review:

class Review < ActiveRecord::Base

 # THIS CLASS DOESN'T FOLLOW RAILS CONVENTION
 # HOW DO I SET AND MANAGE LEGACY PRIMARY KEY?
 # HOW DO I CONNECT THIS MODEL TO THE OTHER DATABASE?
 # HOW DO I CONNECT THIS MODEL TO THE RIGHT TABLE NAME?

 attr_accessible :rv_tbl_title, :rv_tbl_id, :rv_tbl_text, :rv_tbl_author, :rv_tbl_ref_prod

 has_one :Product, foreign_key: :rv_tbl_author

end

Is there a gem for it? What's the solution to use in the Review class questions?

1 Answer 1

3

I'm not sure if this first part is necessary or not, but in your database.yml file, make a new connection by adding something like this to the end:

review:
  adapter: sqlserver
  database: reviews_db
  .... put your other configuration info here

Then in your review model review.rb:

class Review < ActiveRecord::Base
  establish_connection :review
  self.table_name = "review_table"
  self.primary_key = "review_id"
end

Change the table name to the correct table, and the primary key to the correct column name.

Then create a new table/model for the sole purpose of having a local reference to a review. So you could call it ReviewReference

class ReviewReference < ActiveRecord::Base
  belongs_to :review
  has_one :product
end

And change your Product model to

class Product < ActiveRecord::Base
  has_many :reviews, class_name: "ReviewReference"
end

This should get you a long way toward your goal. You might have to end up doing a lot of

@reviews = Review.where("some_column = ?", some_value)

or

@reviews = Review.find_by_sql("Some SQL Here") if you're doing more complex queries.

Sorry my answer isn't more concrete, I've only done this once. Props to Chad Fowler's Rails Recipes book for the concept.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.