簡體   English   中英

Rails 4 / Postgresql 9.4-查詢和更新數組中的ruby對象

[英]Rails 4 / postgresql 9.4 - Query and update a ruby object inside an array

我有一個方法(find_by_sql),它在數組中輸出一個ruby對象,如下所示:

[#<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'屬性?

我嘗試了不同的方式編寫它,但是我偶然發現了它非常具體的事實:它是一個數組,並且內部有一個ruby對象,我必須設法告訴postgresql將deal_available:true的值更改為deal_available:false。

在本地,我嘗試過:logger.debug“這是要更新的結果對象:

 #{@deal_question[0]}

但我得到:

#<@deal_question:0x007fd9b3963270>

這是創建@deal_question的方法

@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對象。

實際上,您實際上不需要原始SQL查詢來更新@deal_question對象的deal_available屬性。

您可以使用update_attributes來實現。

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

如果您確實要使用原始sql更新屬性,請執行以下方法:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM