0

In writing a Rails app there are several places where string table column widths are needed: validations, RSpec testing, input forms, etc. It seems worthwhile to set the length limit on strings in the DB also.

At present I've set a LENGTHS hash in the model so I can access the lengths in other places and keep the code DRY in this respect. If I set the length limits in the DB, is it possible to read the values from there (or initialize the LENGTHS hash with them) to make the code even more DRY? That is, what is the code to read a string length limit of a database column in the model so I can use it?

4

2 回答 2

1

您可以访问 AR 模型的 columns 方法。

Model.columns.map(&:limit)
Model.columns.map(&:name)
Model.columns.map(&:null)
Model.columns.map(&:sql_type)
...

所以你可以使用这个方法来构造你的哈希/数组/任何东西。我相信你所说的长度属性是这个符号的限制

于 2012-06-12T20:34:20.963 回答
0
class ActiveRecord::Base
  def self.method_missing(method_id, *args)
    if self.columns_hash.has_key?(method_id.to_s)
      self.columns_hash[method_id.to_s]
    else
      super
    end
  end
end

columns_hash这允许以干净的方式访问由提供的任何列模式数据。因此:

Model.column_name返回所有可用数据的哈希值

Model.column_name.hash_key返回一个感兴趣的值

例如: Company.contact_name.limit返回列的最大长度contact_name。根据我的阅读,数据库在启动时加载模式数据,因此不会发生数据库命中并columns_hash记忆数据。

于 2012-06-13T05:51:42.583 回答