Rails 3.使用原始SQL或Arel编写ActiveRecord查询

时间:2016-03-13 23:44:58

标签: ruby-on-rails arel

我正在查看遗留代码库,我看到类似这样的内容:

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方法中调用了什么?它是什么?是AREL吗?这是否存在是因为没有ActiveRecord便捷方法可以解决这个问题?是SQL还是Arel?有很好的资源可以快速学习AREL吗?

1 个答案:

答案 0 :(得分:0)

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

这不是AREL。

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