Вопрос

I was curious how rails queries a table that uses STI. For example, if my parent class is Book and I have two subclasses ComicBook and Novel if I do something like

Novel.all.each

since there's only one table, does the server shift through all of the comic books as well? Is appropriate indexing automatically added to prevent this? Thanks

Это было полезно?

Решение

Well, you can't do Novel.each, each isn't defined on model classes. You can however do Novel.all.each ... where ... is some block.

As for how the query works, just call to_sql on any ARel expression. Novel.all will return the collection of models itself, so you need to go a step further to ensure a valid ARel expresion is returned by calling scoped.

[1] pry(main)> Novel.scoped.to_sql
=> "SELECT \"books\".* FROM \"books\" WHERE \"books\".\"type\" IN ('Novel')"

Indexing by most columns that are queried against frequently is a good thing to consider. Yes, without the index your rdbms will have to look at all records in the table as part of the above condition check.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top