Drew Rush
Drew Rush

Reputation: 720

Rails and Active Record: SQL Equivalent

I'm trying to select just one column for many records in a table. This does not produce what I'm looking for. The SQL equivalent of what I'm trying to produce is:

SELECT OneColumn FROM Table WHERE ForeignKey = 1

I've tried many of the suggestions in the Rails Guide for Active Record, but none have worked.

Upvotes: 0

Views: 141

Answers (2)

m_x
m_x

Reputation: 12564

from rails 3.2+ you have #pluck :

Table.where( ForeignKey: 1 ).pluck( :OneColumn )

if you have troubles due to non-conventionnal column or table names, try :

Table.where( Table.arel_table["ForeignKey"].eq 1 ).pluck( Table.arel_table["OneColumn"])

If you just want "low-level" SQL queries, try #select_all or #select_values

Upvotes: 1

Logan Serman
Logan Serman

Reputation: 29880

Use pluck:

Table.where(ForeignKey: 1).pluck(:OneColumn)

Upvotes: 0

Related Questions