简体   繁体   中英

Generating some strange metrics in Rails

I have what would be pretty simple SQL statements but I'm having problems wrapping my mind around them in ActiveRecord. Here's what I've got: a User model that has_many Order s.

Things I'd like to get:

  • A count of the number of orders placed by users that have never ordered from us before (today and this week)
  • A count of the number of orders placed by repeat customers (today and this week)

I feel like this should be a totally normal thing to do, but can't seem to figure it out from the docs. Any guidance would be appreciated!

I don't know how reliant you want to be on doing it 'The Rails Way,' but I have occasionally found that it is handy to know how to just hit the database with a query in exactly the way my mind designed it in the first place:

sql = ActiveRecord::Base.connection
results = sql.select_all("select now()")  #Just a quick example.

You'll get back an array of hashes, where the hash keys are the titles of the columns of each result and the array is simply one hash per row returned by the query. It may not be the answer you were looking for, but I do occasionally get tired of trying to figure out how to do something The Rails Way, and I've been fairly unhappy a couple times when upgrading rails versions got me hung up in complex queries that I bothered to do That Way. I'd rather write it once and be done with it. Your mileage may vary, if your team doesn't tolerate such things. =]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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