Ruby on Rails: Is it possible to use Camel-cased database field and table names?

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

The Ruby on Rails convention for database table and field names is snake_case and not CamelCase. However, I have an existing database being used by a PHP application. I would like to write a Rails application that interacts with this database. Is there an easy, "Rails way" to interact with a database using CamelCase database table and field names?

回答1:

The short answer is yes but it's not always easier than migrating the old database to a new database. If you want both applications to be able to use the same database though then it is probably the quickest approach up front.

You can override the table and foreign key fields by doing the following:

set_table_name "camelCaseName"  set_primary_key "cameCaseIdName"  

You can alias all the field names if necessary as well:

alias "camelCaseFieldName", "field_name" 

All of the AR relationships can set the primary key field as well.

has_many :comments, :foreign_key_id => "commentCamelCaseID" 

It's more work than normal but it is possible.



回答2:

Sure. In your model, just define your table like so:

class FooBar < ActiveRecord::Base   self.table_name = "FooBar" end 

the same holds true for field names, which you can define in your migration or schema. You can assign any name you like. It takes a bit more work unless you want to override the default mechanic, but it's still possible:

create_table "products", :force => true do |t|   t.column "shop_id",    :integer   t.column "creator_id", :integer   t.column "name",       :string,   :default => "Untitled"   t.column "value",      :string,   :default => "Untitled"   t.column "created_at", :datetime   t.column "updated_at", :datetime end 

For more info, see Table Definitions



回答3:

for the datbases tables name you could use set_table_name

  class Dog < ActiveRecord::Base     set_table_name 'dog'   end 

for the field you could override your accessor . hope be usefull . bye



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!