修改find​​_by_sql的返回值

时间:2012-07-07 02:07:53

标签: ruby-on-rails ruby ruby-on-rails-2 ruby-1.8

所以我在这个问题/我的头发上拉头发。基本上我使用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。由于遗留代码,我无法真正升级。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

你试过吗

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