baash05
baash05

Reputation: 4516

getting a column by "name" in an activerecord

I have a select statement that returns a field in a table.

records = Product.select("DISTINCT #{iFieldName}").where("id in (0, #{iInClaws})" )

I want to convert the data in the database to an array to be used later.. say as another inClaws.

records.each{|record| fieldArray << record.?????}

I have two questions.

  1. Is there a better way to do this?
  2. If there's not, then how do I get the data out of the field.


Thanks to all.. After everyone came to help my final method looked like this.

def self.getFieldArray(iFieldName, iIDsInClaws, iIdFieldName = 'id')
    records = self.select("DISTINCT #{iFieldName}").where("#{iIdFieldName} in (#{iIDsInClaws})" )
    return records.map{|record| record.send(iFieldName)};
end

Upvotes: 0

Views: 137

Answers (2)

Ismael
Ismael

Reputation: 16730

fieldArray = records.map(&:iFieldName)

Or

res = records.map{|r| r.send(iFieldName)}

Upvotes: 2

RadBrad
RadBrad

Reputation: 7304

records.each{|record| fieldArray << record.send(iFieldName)}

Upvotes: 2

Related Questions