在Rails DB中使用CamelCase而不是snake_case [英] CamelCase instead of snake_case in Rails DB

查看:161
本文介绍了在Rails DB中使用CamelCase而不是snake_case的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库表和字段名称在CamelCase中.是否可以快速将这些名称转换为snake_case?要使模型方法看起来更漂亮?

My DB tables and field names are in CamelCase. Is it possible to convert those names into snake_case on a fly? To make model methods look pretty?

该应用程序是JRubyOnRails 3.0/MSSQL DB/ActiveRecord-JDBC-adapter.

The app is JRubyOnRails 3.0 / MSSQL DB / ActiveRecord-JDBC-adapter.

推荐答案

@arkadiy,事实上,我只是在这一天才进行调查.

@arkadiy,as a matter of fact, I was looking into this just this very day.

对于表名,我们当然具有 set_table_name 方法:

For table names, we of course have the set_table_name method:

class CamelCasedFoo < ActiveRecord::Base
  set_table_name :CamelCasedTable
end

对于诸如主键之类的东西,我们有 set_primary_key :

For things like primary keys, we have set_primary_key:

class CamelCasedBar < ActiveRecord::Base
  ...
  set_primary_key "CamelCasedTableID"
end

使用 alias_attribute :

class CamelCasedBaz < ActiveRecord::Base
  ...
  alias_attribute :preferred_delivery, :DeliveryFrequency
end

要记住的关键一件事是当心任何红宝石或铁轨名称关键字魔术字段名称.

One key thing to keep in mind is to watch out for any column names that are ruby or rails keywords or magic field names.

Rails似乎具有所有的元编程优点,可让您解决旧数据库表名称和列的问题.您可能希望阅读"Ruby on Rails"上Jonathan Hui的博客文章. 3使用旧版数据库的模型"..您可能想看看 safe_attributes 宝石.

Rails appears to have all that metaprogramming goodness to allow you to work around legacy db table names and columns. You may wish to have a read of Jonathan Hui's blog post on "Ruby on Rails 3 Model Working with Legacy Database". And you might want to have a look at the safe_attributes gem.

这篇关于在Rails DB中使用CamelCase而不是snake_case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆