我有一个遗留数据库,其中包含一堆愚蠢命名的列,例如:
some_field_c some_other_field_c a_third_field_c
I would very much like to make a Rails ActiveRecord sub-class that automatically aliases these attributes to their name minus the underscore and "c". However, when I tried:
attributes.each_key do | key |
name = key
alias_attribute key.to_sym, key[0, (key.length -2)].to_sym if key =~ /_c$/
end
在我的类定义中,我遇到了“未定义的局部变量或方法‘属性’”错误。我还尝试覆盖这些方法:
method_missing respond_to?
但我也一直在这条路线上出错。
所以我的问题(实际上是问题)是:
- 我尝试做的事情是否可行?
- 如果是这样,最好的方法是什么(迭代别名或覆盖方法缺失)?
- 如果不是太麻烦的话,关于如何执行 #2 的非常简短的代码示例会很棒。
提前感谢您对本文收到的任何答复。
最佳答案
您的问题可能是 attributes
是一个实例方法,而您是在类的上下文中这样做的。最接近您想要的类方法是 column_names
。
关于ruby-on-rails - rails ActiveRecord : Automatically Alias/Append Suffix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/509741/