【问题标题】:Modifying the returned value of find_by_sql修改 find_by_sql 的返回值
【发布时间】:2012-07-07 11:23:41
【问题描述】:

所以我在这个问题/问题上拉了我的头发。基本上我使用 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 是否返回数组哈希? 是否可以修改上述hash的属性之一的值?

这里是代码:http://pastie.org/4213454。如果您可以查看summarize_roles2(),那就是行动发生的地方。

谢谢。我使用 Rails 2.1.1 和 Ruby 1.8。由于旧代码,我无法真正升级。

【问题讨论】:

  • 不要认为某些东西会更慢/更快,对这两种方法进行基准测试并知道哪个更快(如果它足够快值得)。

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


【解决方案1】:

你试过了吗

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

【讨论】:

    【解决方案2】:

    只要改变上面的方法来访问值,打印项目的值,就可以清楚地查看对象属性了。

    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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 2017-09-05
      • 2013-10-22
      相关资源
      最近更新 更多