How to query data without creating a model in Rails?

Sometimes I have to query a large amount of data in a database for data processing.

For example, I have a table: Activity, I want to find all the users who create activity in the last month,

I’m only concerned about data arrays, and I don’t want to create many action models,

Can I do this?

like this code:

Activity.where('created_at > ?', Time.now - 1.month).get_data(:user_id, :created_at) => [[1, 2012-02-01] .... ] 
+6
source share
2 answers

Try this approach:

 sql = "SELECT * from activities limit 10" result = ActiveRecord::Base.connection.execute(sql) result.to_a 

I'm not sure about sql query, but I think you get the idea.

+6
source

Try:

 Activity.where(['activities.user_id = ? AND activities.created_at BETWEEN ? AND ?', users, 1.month.ago, Time.zone.now]) 

This will return all activities that were created in the last month for recruiting users. The only potential problem with this query is the extremely large datasets. You might want to use named_scope to narrow down the actions before running this query so that it does not search every activity in db.

0
source

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


All Articles