【问题标题】:Rails 3. Writing ActiveRecord queries with raw SQL or ArelRails 3. 使用原始 SQL 或 Arel 编写 ActiveRecord 查询
【发布时间】:2016-03-13 23:44:57
【问题描述】:

我正在浏览一个遗留代码库,我看到类似这样的内容:

def all_story_links
    StoryLink.complete.where("
      (storyable_type = 'Recipe' AND storyable_id = ?)
      OR
      (storyable_type = 'RecipeStep' AND storyable_id IN (?))
      OR
      (storyable_type = 'RecipeIngredient' AND storyable_id IN (?)
      )", id, recipe_step_ids, recipe_ingredient_ids)
  end

在 where 方法中调用了什么?它是什么?是阿雷尔吗?这是否存在,因为没有解决此问题的 ActiveRecord 便捷方法?是 SQL 还是 Arel?有什么好的资源可以快速学习 AREL?

【问题讨论】:

  • "在 where 方法里面叫什么?" -> 一个 SQL 查询...?不,这不是使用 arel 包装器。要求教程不是 Stack Overflow 的主题。抱歉 :-( Ruby on Rails Guides 非常好,应该为您提供大部分入门信息。

标签: ruby-on-rails arel


【解决方案1】:

where 方法中的内容主要是普通的旧 SQL,Rails 的附加功能会在它看到问号(“?”)的地方进行替换。 Rails 替换了问号,即在查询本身之后赋予 where 方法的值:id, recipe_step_ids....

这不是 AREL。

在这种情况下可能使用了普通的旧 SQL,因为使用 ActiveRecord API 很难或不可能实现 AND 和 OR。

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    相关资源
    最近更新 更多