代码之家  ›  专栏  ›  技术社区  ›  rtacconi

ActiveRecord:使用字符串中的模型进行查询

  •  2
  • rtacconi  · 技术社区  · 14 年前

    我有一个包含一组ActiveRecord模型的字符串,我想对作为字符串传递的每个模型执行相同的查询。

    model_type = 'Comment'
    id = 1
    record = model_type.find(id)
    
    model_type = 'Post'
    id = 1
    record = model_type.find(id)
    

    我该怎么做?

    2 回复  |  直到 14 年前
        1
  •  4
  •   tadman    14 年前

    你需要使用 constantize 方法。

    model_type.constantize.find(id)
    

    在接受任意用户数据并按此方式进行计算时,请务必小心。您可以为未知类生成异常。

        2
  •  1
  •   Dan Harper    14 年前

    constantize 很好,我以前没见过那个。我以前是这样做的:

    @list = Kernel.const_get(@type).find_by_id_and_account_id(params[:id], current_account.id)
    

    我不确定哪个更好, 恒常化 看起来更干净:)