开发者

Generating some strange metrics in Rails

开发者 https://www.devze.com 2023-02-09 07:15 出处:网络
I have what would be pre开发者_如何学编程tty 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 Orders.

I have what would be pre开发者_如何学编程tty 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 Orders.

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. =]

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号