简体   繁体   English

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

[英]Rails 3. Writing ActiveRecord queries with raw SQL or Arel

I am looking through a legacy codebase and I see something like this: 我正在查看旧版代码库,发现如下所示:

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

What is that called inside the where method? 在where方法里面叫做什么? What is it? 它是什么? Is it AREL? 是AREL吗? Does this exist because there is no ActiveRecord convenience methods that resolves to this? 这是否存在是因为没有ActiveRecord便捷方法可以解决这个问题? is it SQL or Arel? 是SQL还是Arel? Got any good resources to learn AREL quickly? 有什么好的资源可以快速学习AREL吗?

What's inside the where method is mostly plain old SQL, with the added feature of Rails doing substitutions wherever it sees the question marks ("?"). where方法中的内容大部分是普通的旧SQL,Rails的附加功能是在看到问号(“?”)的任何地方进行替换。 Rails substitutes for the question marks, the values given to the where method after the query itself: id, recipe_step_ids.... . Rails代替了问号,即查询本身后给where方法的值: id,recipe_step_ids ....。

It is not AREL. 这不是AREL。

The plain old SQL was probably used in this case because the ANDs and ORs would have been difficult or impossible to implement using the ActiveRecord API. 在这种情况下,可能使用普通的旧SQL,因为使用ActiveRecord API很难或不可能实现AND和OR。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM