Implement 'Select column_name from table_name where condition' in Active Record

I needed an array from the data contained in a particular database column based on a condition, so i get the array of active record rows:

array_of_rows = TableName.find(:all, :conditions => {:column_name => [‘col_data1’,‘col_data2’]})

Then use the array map! function to replace the active record objects with the column_name value!{|item| item.column_name}

Doing some search got me:

array_of_rows = TableName .find(:all,:select=>‘column_name’ :conditions => {:column_name => [‘col_data1’,‘col_data2’]}).map(&:column_name)

And i like this better, concise ….

I’ve had to update the active record query above by removing the :select option

array_of_rows = TableName .find(:all, :conditions => {:column_name => [‘col_data1’,‘col_data2’]}).map(&:column_name)

This is because if i have a method

def find_some_data
TableName .find(:all,:select=>‘column_name’ :conditions => {:column_name => [‘col_data1’,‘col_data2’]})

I am able to do:

but i cannot do

throws: missing attribute: another_column_name (ActiveRecord::MissingAttributeError)

because i have only retrieved ‘column_name’ values from the table

In other to be able to create any array composed of data from any column_name, i have

def find_some_data
TableName .find(:all, :conditions => {:column_name => [‘col_data1’,‘col_data2’]})

You Might Also Like
comments powered by Disqus