问题
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?
回答1:
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
- http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name-3D
- http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html#method-i-primary_key-3D
回答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
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/31545206/connect-rails-application-to-existing-database