ActiveRecord Select with Parameter Binding

前端 未结 1 725
孤街浪徒
孤街浪徒 2021-01-05 21:20

I want to use a subquery with ActiveRecord like so:

User.select(
    \'users.*, 
    (select sum(amount) 
        from subscriptions 
        where subscript         


        
1条回答
  •  执笔经年
    2021-01-05 21:44

    You can use one of the ActiveRecord::Sanitization class methods.

    These are mixed into ActiveRecord::Base and are almost all protected so they are most easily accessed by defining a class method on your model:

    class User < ActiveRecord::Base
      def self.select_with_args(sql, args)
        query = sanitize_sql_array([sql, args].flatten)
        select(query)
      end
    end
    

    It's also worth looking for other ways to fetch your data and comparing their performance to the subquery method. For example, you could fetch the subscription counts with a separate query:

    subs_by_user = Subscription.group(:user_id).where('created_at < ?', d).count()
    

    0 讨论(0)
提交回复
热议问题