2012-07-07 56 views
0

因此,我在這個問題/疑難問題上拉我的頭髮。基本上我使用find_by_sql從我的數據庫中獲取數據。我這樣做是因爲查詢有很多列和表連接,我認爲使用ActiveRecord和關聯會減慢它。修改find​​_by_sql的返回值

我設法拉出數據,現在我想修改返回的值。例如,我通過循環遍歷結果來完成此操作。

a = Project.find_by_sql("SELECT mycolumn, mycolumn2 FROM my_table").each do |project| 
    project['mycolumn'] = project['mycolumn'].split('_').first 
end 

我發現的是project['mycolumn']根本沒有改變。

所以我的問題:

find_by_sql返回數組哈希? 如上所述是否可以修改哈希屬性之一的值?

這裏是代碼:http://pastie.org/4213454。如果你可以看看summarize_roles2()這就是行動發生的地方。

謝謝。我使用Rails 2.1.1和Ruby 1.8。由於遺留代碼,我無法真正升級。

+0

不要* *想的東西會比較慢/快,標杆兩種方法和*知道*這是更快(如果它足夠快,值得)。 – 2012-07-07 04:41:09

回答

0

只要改變上面的方法來訪問值,打印項目的價值,你可以清楚地檢查對象的屬性。

The results will be returned as an array with columns requested encapsulated as attributes of the model you call this method from.If you call Product.find_by_sql then the results will be returned in a Product object with the attributes you specified in the SQL query. 
If you call a complicated SQL query which spans multiple tables the columns specified by the SELECT will be attributes of the model, whether or not they are columns of the corresponding table. 
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" 
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] 

來源:http://api.rubyonrails.org/v2.3.8/

0

你試過

a = Project.find_by_sql("SELECT mycolumn, mycolumn2 FROM my_table").each do |project| 
    project['mycolumn'] = project['mycolumn'].split('_').first 
    project.save 
end