0

所以我在这个问题/问题上拉扯我的头发。基本上我使用 find_by_sql 从我的数据库中获取数据。我这样做是因为查询有很多列和表连接,我认为使用 ActiveRecord 和关联会减慢它的速度。

我设法提取数据,现在我想修改返回值。例如,我通过循环遍历结果来做到这一点。

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。由于遗留代码,我无法真正升级。

4

2 回答 2

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/

于 2012-07-07T04:05:59.020 回答
0

你有没有尝试过

a = Project.find_by_sql("SELECT mycolumn, mycolumn2 FROM my_table").each do |project|
  project['mycolumn'] = project['mycolumn'].split('_').first
  project.save
end
于 2012-07-07T13:29:26.457 回答