Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get columns names with ActiveRecord

Is there a way to get the actual columns name with ActiveRecord?

When I call find_by_sql or select_all with a join, if there are columns with the same name, the first one get overridden:

select locations.*, s3_images.* from locations left join s3_images on s3_images.imageable_id = locations.id and s3_images.imageable_type = 'Location' limit 1 

In the example above, I get the following:

#<Location id: 22, name: ...  > 

Where id is that of the last s3_image. select_rows is the only thing that worked as expected:

Model.connection.select_rows("SELECT id,name FROM users") => [["1","amy"],["2","bob"],["3","cam"]] 

I need to get the field names for the rows above. This post gets close to what I want but looks outdated (fetch_fields doesn't seem to exist anymore How do you get the rows and the columns in the result of a query with ActiveRecord? )

The ActiveRecord join method creates multiple objects. I'm trying to achieve the same result "includes" would return but with a left join.

I am attempting to return a whole lot of results (and sometimes whole tables) this is why includes does not suit my needs.

like image 701
Abdo Avatar asked Jun 13 '12 08:06

Abdo


People also ask

How do I get column names in an array?

Columns attribute of the dataframe returns the column labels of the dataframe. You can get the column names as an array by using the . columns. values property of the dataframe.

What is ActiveRecord naming convention?

Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns. Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id , order_id ).

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is ActiveRecord relation?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.


1 Answers

Active Record provides a #column_names method that returns an array of column names.

Usage example: User.column_names

like image 58
TheIrishGuy Avatar answered Sep 22 '22 12:09

TheIrishGuy