Problem: To retrive a specific column by method.find


#1

hi guys,
the method all_data retrive all data from a table
def all_data
@output_column = OutputColumn.find :all
end

But I want to retrive a person_name column to generate a list of all
person…
so how can i do it?

Thx in advanced.

Milinda


#2

Eric Milinda wrote:

hi guys,
the method all_data retrive all data from a table
def all_data
@output_column = OutputColumn.find :all
end

But I want to retrive a person_name column to generate a list of all
person…
so how can i do it?

I have thought that the previous solution can be achieved by the
following code.

def fil_string
sql = ActiveRecord::Base.connection()
filter_string=’ ’
sql.begin_db_transaction
column_ids = sql.execute(“SELECT columnid FROM output_columns”)
column_ids.each do |column_id|
filter_string=filter_string +" columnid=’"+column_id+"’"
end
sql.commit_db_transaction
end

but in the solution
Error: can not convert array to string
at line – filter_string=filter_string +" columnid=’"+column_id+"’" "

Please take a hand in my code.

thx.


#3

ActiveRecord works at the row (aka record) level, not the column
level. That’s not to say that you can’t just get a single column of
data back from the database, you can, but you won’t have all the
attributes if you do this so just keep that in mind. you’ll probably
want to map them to an array

try something like:

class User < ActiveRecord::Base
def self.names
# find all records, then map name attributes to an array
find(:all, :select => “name”).map(&:name)
end
end

then just do

@names = User.names

in your controller methods where you need it

btw

.map(&:name)

is shorthand for

.map { |x| x.name }