Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query data without create model in Rails?

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] .... ]
like image 349
linjunhalida Avatar asked Jul 30 '12 08:07

linjunhalida


People also ask

Can we create a table without a model in Rails?

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.

What is eager loading rails?

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!

What are active records in Rails?

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.


1 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.

like image 69
megas Avatar answered Nov 29 '22 01:11

megas