轨道4 / PostgreSQL的9.4 - 查询和更新数组内的Ruby对象 [英] Rails 4 / postgresql 9.4 - Query and update a ruby object inside an array

查看:236
本文介绍了轨道4 / PostgreSQL的9.4 - 查询和更新数组内的Ruby对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法(的find_by_sql)的输出数组内的Ruby对象是这样的:

I have a method (find_by_sql) that outputs a ruby object inside an array like this:

[#<deal id: 66480, opportunity_id: 4, admin_user_id: 1, created_at: "2015-09-20 18:37:29", updated_at: "2015-09-20 18:37:29", deal_available: true>]

我怎么能在我的原材料PostgreSQL数据库内更新对象deal_available'属性?

How can I update the object's 'deal_available' attribute inside my database in raw postgresql ?

我尝试不同的方式来写,但我绊倒的事实,这是非常特殊:它是一个数组,里面有一个Ruby对象,我必须设法告诉PostgreSQL的为修改的deal_available值:真到deal_available:假

I tried different ways to write it but I stumble on the fact that it's very specific: it's an array, and inside there is a ruby object and I must manage to tell postgresql to change the value of deal_available: true to deal_available: false.

在的地方,我想:logger.debug这里是更新生成的对象:

In local, I tried: logger.debug "Here is the resulting object for update:

 #{@deal_question[0]}

但我得到:

#<@deal_question:0x007fd9b3963270>

下面是如何@deal_question创建

Here is how @deal_question is created

@deal_question = Deal.find_by_sql(
      " SELECT \"deals\".*
        FROM \"deals\"
        WHERE (opportunity_id = #{@deal.id}
        AND deal_available = true)
        ORDER BY \"deals\".\"id\" ASC LIMIT 1"
    ) 

我甚至不有PostgreSQL的查询到在这里建议,因为首先我需要了解如何查询数组,这里面的Ruby对象。

I don't even have a postgresql query to suggest here because first I need to understand how to query this ruby object inside the array.

推荐答案

您其实并不需要一个原始SQL查询来更新你的<$ C的 deal_available 属性$ C> @deal_question 对象。

You actually don't need a raw SQL query to update the deal_available attribute of your @deal_question object.

您可以使用 的update_attributes来实现这一目标。

You can use update_attributes to achieve that.

# assuming @deal_question is an array
@deal_question[0].update_attributes(deal_available: false)

如果你真的想使用原始SQL来更新属性,然后做这样的:

If you really want to use raw sql to update the attribute, then do this way:

array = [#<deal id: 66480, opportunity_id: 4, admin_user_id: 1, created_at: "2015-09-20 18:37:29", updated_at: "2015-09-20 18:37:29", deal_available: true>]
# grab the object to be updated
@deal_question = array[0]
# build the sql query string
sql = "UPDATE deals SET deal_available = false WHERE opportunity_id = #{@deal_question.id}"
# execute the sql to update the object
ActiveRecord::Base.connection.execute(sql)

这篇关于轨道4 / PostgreSQL的9.4 - 查询和更新数组内的Ruby对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆