My blog has moved!
You should be automatically redirected in 5 seconds. If not, visit http://samueladesoga.wordpress.com and update your bookmarks.

Friday 23 April 2010

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

I need 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
array_of_rows.map!{|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 ....
update:

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']})
end

I am able to do:

find_some_data.map(&:column_name)

but i cannot do

find_some_data.map(&:another_column_name)

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']})
end

Tuesday 6 April 2010

Active Record find by Column Name

In recent days been doing a lot of ruby, which means i tend to use Active Record as well.

I had written some scripts where i was selecting records that matched a criteria such as:

@table1.table2s.select{|e| e.column_name == 1234}

but as i need to sort my result and also give some more conditions to filter the data, i need alternatives to this above query and i ended up with the two lines of code below:

@table1.table2s.find(:all, :conditions => {:column_name => 1234})
@table1.table2s.find_all_by_column_name(1234)

Please note that the two lines above does same thing, the second one is just a lil but shorter and more readable the the 1st one.

using the second one i can now do stuff like

@table1.table2s.find_all_by_column_name(1234, :order => "col_2 ASC")

which would order my results based on the column that i have specified and i could have ASC - ascending and DESC - descending.

I have learnt something else today .... Have you?