Confused about the behavior of returned object

37 views Asked by At

After firing a Model.find_by_sql as;

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

The object is returned as;

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

On using the 'inspect' function on data,it retruns

[#<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">]

On using data.class it returns Array.

However, this works just fine on using as a 'hash' as far as i presume,

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>
    })

My question here is, why does 'data' behaves like an Hash, as per the implementation like 'name.value'.

Thanks

1

There are 1 answers

0
Nitish Parkar On BEST ANSWER

find_by_sql is returning an array of Setup::Type objects. When you are iterating over the array, you are getting an instance of Setup::Type which you are accessing using name variable. Hence name.value is working.

If you change name to type_obj, it would be more clear,

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>
    })

This is from the documentation of find_by_sql. Might help.

Executes a custom SQL query against your database and returns all the results. 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.