ruby-on-rails - rails ActiveRecord : Automatically Alias/Append Suffix?

标签 ruby-on-rails ruby activerecord attributes

我有一个遗留数据库,其中包含一堆愚蠢命名的列,例如:

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?

但我也一直在这条路线上出错。

所以我的问题(实际上是问题)是:

  1. 我尝试做的事情是否可行?
  2. 如果是这样,最好的方法是什么(迭代别名或覆盖方法缺失)?
  3. 如果不是太麻烦的话,关于如何执行 #2 的非常简短的代码示例会很棒。

提前感谢您对本文收到的任何答复。

最佳答案

您的问题可能是 attributes 是一个实例方法,而您是在类的上下文中这样做的。最接近您想要的类方法是 column_names

关于ruby-on-rails - rails ActiveRecord : Automatically Alias/Append Suffix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/509741/

相关文章:

mysql - Rails 事件记录查询以特定顺序获取数据

ruby-on-rails - 恢复 postgres 数据库备份时出错

java - 尝试在 Rails Heroku 应用程序上安装 Java

jquery - Facebook 社交按钮在 jquery/rails 中不起作用

css - Codekit 和 Zurb Foundation 错误

ruby - 方法调用的符号

ruby-on-rails - 如何翻译 "Model Name could not be saved".?

不同类之间的 Ruby TempFile 行为

ruby-on-rails - 在 Rails 3 中为所有目的继承模型和更改表

ruby-on-rails - ActiveRecord::Relation 返回不同的类对象