Forum: Ruby on Rails Problem: To retrive a specific column by method.find

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D521111af37224f4659919c514de1902?d=identicon&s=25 Eric Milinda (eric_milinda)
on 2007-04-19 10:18
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
D521111af37224f4659919c514de1902?d=identicon&s=25 Eric Milinda (eric_milinda)
on 2007-04-19 11:33
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.
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (au5lander)
on 2007-04-19 14:36
(Received via mailing list)
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 }
This topic is locked and can not be replied to.