Sometimes, I need to query lots of data in DB for data processing.
For example, I have a table: Activity, I want to find all the users which create activity in the last month,
I am only concerned about the data arrays, and I don't want to create a lot of Activity models,
Is there any way I can do it?
like this code:
Activity.where('created_at > ?', Time.now - 1.month).get_data(:user_id, :created_at)
=> [[1, 2012-02-01] .... ]
There is no harm in creating a Model for a table in Rails. Though, if you wish to avoid it, you can use raw SQL queries for same.
Eager loading lets you preload the associated data (authors) for all the posts from the database, improves the overall performance by reducing the number of queries, and provides you with the data that you want to display in your views, but the only catch here is which one to use. Gotcha!
Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With