6

我的数据库表和字段名称在 CamelCase 中。是否可以即时将这些名称转换为snake_case?让模型方法看起来很漂亮?

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

4

4 回答 4

6

@arkadiy,事实上,就在这一天,我正在调查这个问题。

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

class CamelCasedFoo < ActiveRecord::Base
  set_table_name :CamelCasedTable
end

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

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

并且应该可以将时髦的、遗留的列名别名为对 rails 更友好的名称alias_attribute

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

要记住的关键一件事是注意任何列名称是 ruby​​ 或 rails关键字魔术字段名称

Rails 似乎具有所有元编程优点,可以让您处理遗留的数据库表名和列。您可能希望阅读 Jonathan Hui 关于“Ruby on Rails 3 Model Working with Legacy Database”的博文。您可能想看看safe_attributes gem。

于 2011-05-13T15:57:55.590 回答
1

我也有同样的需要。@buruzaemon 设置 table_name 和 primary_key 的答案很好,但我有一些建议可以让它变得更好。

我相信 set_* 风格的方法已经失宠,现在建议直接设置属性。所以

class Project < ActiveRecord::Base
  self.table_name = 'Projects'
  self.primary_key = 'ProjectId'
end

此外,使用 alias_attribute 手动为每个属性设置别名似乎很乏味。似乎也很容易忘记一个。尽管@Behrangf 建议不要这样做,但我认为使用一点元编程魔法来自动提供属性的snake_case 版本没有任何问题。我创建了一个自动执行此操作的模块。它甚至与 ActiveRecord 无关,因此您也可以在 API 包装器或其他镜像不遵循 Ruby 约定的系统的东西中使用它。我正在跟踪 Gist 上的模块,但为方便起见,转载如下:

module Snakeable

  # Patch in our automatic snake_case methods
  def method_missing method, *args 
    if is_snake_case?(method) &&
      respond_to?(camelized = method.to_s.camelize.to_sym)
      send camelized, *args
    else
      super
    end
  end

  # So the object including this module will respond to
  # Object#respond_to? correctly
  def respond_to? method, *args
    super || (
      is_snake_case?(method) &&
      super(method.to_s.camelize.to_sym, *args)
    )
  end

  private

  # Is the given method using the snake_case format
  def is_snake_case? method
    method.to_s =~ /^[a-z]+(?:_[a-z]+)*[?=!]?$/
  end

end

这个模块确实依赖于 ActiveSupport 的camelize方法。

于 2014-04-02T18:26:32.427 回答
0

Ruby on Rails is opinionated software. It means that its designers have chosen to do things in a specific way and in order to be able to use RoR with success, pleasure, ease, smoothness, etc. you must do it in that specific way. As such if you can't or don't want to follow RoR's table and column naming conventions you are advised to select another framework.

However if you want to stay with RoR yet you want snake_case method names, you can open the ActiveRecord::Base class, intercept calls to undefined methods, ensure that they match the ^[a-z]+(_[a-z]+)*$ regular exception, and if so, convert them to the upper case and call the upper case method. BUT I STRONGLY ADVISE YOU NOT TO DO THAT!!!* :D

于 2011-05-13T11:43:16.170 回答
0

呸!你有我的同情。我一直喜欢 old_school.names,即使引擎允许其他恶意软件......

我认为这是一个旧版应用程序?

为您的 Rails 应用程序创建一组视图如何?

于 2011-05-13T01:16:36.637 回答