开发者

Ruby on Rails ActiveRecord find_by-sql field names

I'm doing custom find_by_sql queries which are dynamically created by user input. What is the best way to find the field names returned by find_by_sql

I've tried using columns, column_names and k开发者_Go百科eys methods but none work. Is the ActiveRecord result a hash or an array?

e.g.

@fm_reports = FmReport.find_by_sql(crosstab_query)
field_names = @fm_reports.keys (or .columns or .column_names)

Cheers, Keith

Update ::

It seems that unless you do "select * from ...." in a find_by_sql it does not return the attribute names

>> FmReport.find_by_sql("select object_class, alarm_mr from fm_reports limit 1") 
=> [#<FmReport >] 
>> FmReport.find_by_sql("select * from fm_reports limit 1") 
=> [#<FmReport id: 7, ALARM_DN: "PLMN-PLMN/BSC-31569/TCSM-72", ALARM_OBJECT: "MELB_BSC1", ALARM_MR: "VIC_METRO", PARENT_DN: "PLMN-PLMN/BSC-31569", PARENT_CLASS: "BSC", OBJECT_CLASS: "TCSM", ALARM_NUMBER: "2955", ALARM_TIME: "21/12/2009 11:02:19", CANCEL_TIME: "21/12/2009 11:03:27", SEVERITY: "2", created_at: nil, updated_at: nil>] 


@fm_reports = FmReport.find_by_sql(crosstab_query)
field_values = @fm_reports.attributes
field_values.each {|key, value| puts key}

The above line will return a hashmap of field-names and their values. They can be iterated on if req.


http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002353

attribute_names


Maybe you're looking for #attributes?

Also, find_by_sql returns an Array so that's why there's no method called attributes. How about doing first.attributes on the result of your find?

Another question is why are you using find_by_sql at all?

Why not just use ActiveRecord's built in stuff for this?

SomeModel.find( :all, :limit => 1 ).first.attributes


I know this is old, but it might help anyone with the same question.
I usually do it like this:

@fm_reports = FmReport.find_by_sql(crosstab_query)
field_names = @fm_reports.first.attributes.keys
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜