2

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?

4 Answers 4

7

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
2

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
1

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
2
  • Thanks I'll look at that as well, but @Phillip answered first, and it seems like the more conventional way of going.
    – richbai90
    Jul 21, 2015 at 17:16
  • No problem. You probably don't want to set the table name of all those tables if they conform to this pattern Jul 21, 2015 at 17:20
0

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.