簡體   English   中英

對返回對象的行為感到困惑

[英]Confused about the behavior of returned object

觸發Model.find_by_sql之后;

data = Setup::Type.find_by_sql ["SELECT value FROM table WHERE type_cd = 'print_format' AND subtype_cd = 'schedule_print_format'"]

對象返回為;

#<Setup::Type:0x60c42f0>
#<Setup::Type:0x60c4140>
#<Setup::Type:0x60c3f90>

在對數據使用“檢查”功能時,它將重新運行

[#<Setup::Type value: "SalesReceipt_Bhindi_sch.rpt">, #<Setup::Type value: "SpecialOrder_Bhindi_sch.rpt">, #<Setup::Type value: "ReturnReceipt_Bhindi_sch.rpt">, #<Setup::Type value: "Takepayment_Bhindi_sch.rpt">]

使用data.class時,它返回Array。

但是,據我推測,這在用作“哈希”時效果很好,

data.each do |name|
  xml  =  Hpricot::XML(%{
                   <params>
                    <from_trans_date>#{date_for_transaction}</from_trans_date>
                    <to_trans_date>#{date_for_transaction}</to_trans_date>
                    <print_format>#{name.value}</print_format>
                    <company_id>#{company_id}</company_id>
                   </params>
    })

我的問題是,為什么像“ name.value”這樣的實現,“數據”的行為像哈希一樣?

謝謝

find_by_sql返回一個Setup::Type對象的數組。 在數組上進行迭代時,將獲得要使用name變量訪問的Setup::Type的實例。 因此, name.value在工作。

如果您將name更改為type_obj ,那就更清楚了,

data.each do |type_obj|
  xml  =  Hpricot::XML(%{
                   <params>
                    <from_trans_date>#{date_for_transaction}</from_trans_date>
                    <to_trans_date>#{date_for_transaction}</to_trans_date>
                    <print_format>#{type_obj.value}</print_format>
                    <company_id>#{company_id}</company_id>
                   </params>
    })

這來自find_by_sql的文檔。 可能有幫助。

對您的數據庫執行自定義SQL查詢,並返回所有結果。 結果將作為數組返回,其中請求的列封裝為調用此方法的模型的屬性。 如果調用Product.find_by_sql,則結果將在具有您在SQL查詢中指定的屬性的Product對象中返回。

暫無
暫無

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

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