Ruby on Rails: create related models with find_by_sql?

Apparently, include and select cannot be used simultaneously in a Rails search query, and this has been repeatedly noted as wontfix:
http://dev.rubyonrails.org/ticket/7147
http://dev.rubyonrails.org/ticket/5371

This seems very inconvenient to me, because the time that I would like to use is exactly the same times when I would like to use select - when every bit of performance is counted.

Is there a way around this and manually create a combined include-with-select using find_by_sql or any other method? The problem is that I don’t know how you can emulate include functionality, where it creates models in memory to store included related models, so I can enter model1.associated_models and not delete it again.

+4
source share
1 answer

Have you considered creating a model to represent a database? For instance:

  • Create a database view with a complex SQL query:

    CREATE VIEW production_plan_items AS SELECT * FROM [...] INNER JOIN [...]; 
  • Create a model for this view:

     # app/view_model.rb class ViewModel < ActiveRecord::Base self.abstract_class = true def readonly? true end def before_destroy raise ActiveRecord::ReadOnlyRecord end end # app/models/logical/production_plan_item.rb module Logical class ProductionPlanItem < ::ViewModel end end 
  • Use as always, but remember that these entries are ONLY READ!

     Logical::ProductionPlanItem.where( ... ) 

If performance continues to be a problem in the future, you can easily convert database views to materialized views using triggers and stored procedures. This will significantly increase the speed of your application, and you won’t have to change even one line of Rails code.

Enterprise Rails is recommended to read: http://www.amazon.com/Enterprise-Rails-Dan-Chak/dp/0596515200/ref=sr_1_1?ie=UTF8&qid=1293140116&sr = 8-1

+4
source

Source: https://habr.com/ru/post/1303195/


All Articles