richbai90
richbai90

Reputation: 5204

Connect Rails Application To Existing Database

I have a client asking me to help them build a ruby application to interface with a database that was created for a different application that runs on php. The problem is that since the database was not scaffolded with rails, it does not follow any of the rails conventions. For example, there is a table called form

If I run the command rails generate model form then rails will infer the table name is forms

further more I don't want ruby to perform any migrations since the data is already there in the state that I want it. Is there any good way of going about this?

Upvotes: 2

Views: 4318

Answers (4)

Unixmonkey
Unixmonkey

Reputation: 18784

Specify the connection details as usual in config/database.yml

production:
  adapter: mysql
  host: somehost.somedomain.com
  port: 3306
  user: sqluser
  password: **********

You can specify the table name for an ActiveRecord model that doesn't conform to Rails conventions like so:

class Form < ActiveRecord::Base
  self.table_name = 'tblForms_tbl'
end

If some of the column names are troublesome, like reserved words or columns with special meaning to ActiveRecord (like "type"), then you can set up custom accessors for them, or use alias_attribute.

class Form < ActiveRecord::Base
  self.table_name = 'tblForms_tbl'
  self.primary_key = 'formID'
  self.inheritance_column = :_type_disabled

  alias_attribute :formsTitle, :title

  # use self.category as an accessor for the "type" column
  def category=(type)
    attr_writer :type, type
  end

  def category
    attr_reader :type
  end

end

Upvotes: 2

R&#233;mi Delhaye
R&#233;mi Delhaye

Reputation: 814

The rails g model ModelName --migration=false command will do the job, this command will create your Model ModelName without the migration.

Moreover, you'll need to specify the real column name for each models as:

Rails >= 3.2 (including Rails 4+):

class ModelName < ActiveRecord::Base
  self.table_name = 'custom-table-name'
end

Rails <= 3.1:

class ModelName < ActiveRecord::Base
  self.set_table_name 'custom-table-name'
end

Upvotes: 0

There are some options to work with legacy databases. If tables are singular you could set that in your config/application.rb

config.active_record.pluralize_table_names = false

Upvotes: 1

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

You don't need to run migrations to have the model. Either skip them (--no-migration) or remove the file after generating. As for table names, look at table_name=. primary_key= may also be handy.

class Form << ActiveRecord::Base
  self.table_name = 'form'
end

Upvotes: 7

Related Questions