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

前端 未结 3 1685
无人及你
无人及你 2021-01-20 11:20

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 woul

相关标签:
3条回答
  • 2021-01-20 11:27

    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.

    0 讨论(0)
  • 2021-01-20 11:29

    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

    0 讨论(0)
  • 2021-01-20 11:40

    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

    0 讨论(0)
提交回复
热议问题