【问题标题】:List reference columns of a active record model列出活动记录模型的参考列
【发布时间】:2013-03-08 22:33:16
【问题描述】:

使用 Rails 3.2,有没有办法找出列是否是其他模型的引用列?

我不想在名称中依赖“_id”字符串搜索。

谢谢。

更新:

我需要遍历所有列并在引用列中进行特殊处理,例如:

result = Hash.new
self.attribute_names.each do |name|
  if self[name]
    result[name] = self[name]

    if name is reference column
       insert xxx_description (from the other model) in hash.
    end
  end
end

我会将此哈希作为 json 返回给客户端。

{name:'joseph',sector_id:2,sector_name:'backend'...}

sector_name 是 person.sector.name...

谢谢。

【问题讨论】:

  • 你为什么需要这个?
  • @onurozgurozkan 是的,有点上下文会很好。对于我能想到的任何问题,可能有比使用列更好的解决方案
  • 对不起,我刚刚更新了我的问题。
  • 感谢您接受我的回答,但现在我有了更多的上下文,我想说,如果可能的话,使用 as_jsonto_jsoninclude 之类的选项会简单得多, 是约定。见jonathanjulian.com/2010/04/rails-to_json-or-as_json

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

如果您不知道协会名称的替代方法:

Post.reflect_on_all_associations(:belongs_to).map &:foreign_key 
# => ['author_id','category_id']

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多