Re: A basic collections/hash question

Mukund
Wed, 09 Sep 2009 11:25:07 -0000

params[:subscribers].each do |subscriber_hash|
   my_record = SubscriberModel.new(subscriber_hash)
   my_record.save
end if params[:subscribers]

Assuming that SubscriberModel is an activerecord model that maps to a
table with similar layout as the hash.

Otherwise, define your own class with an initializer method like so
and do whatever you want with it.

class SubscriberModel
  attr_accessor :name, :msidsm, :imsi, :imei
  def initialize(init_hash={})
    @name = init_hash["name"]
    @msidsm = init_hash["msidsm"]
    @imsi = init_hash["imsi"]
    @imei = init_hash["imei"]
  end
end

----------------------

Alternatively, I could be way off base.  Let me know if it works for
you. :p


On Sep 9, 2:23 pm, comopasta Gr
<rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>
wrote:
> Hi,
>
> I give up trying. I need to ask this basic question about collections
> and hashes.
>
> I''m trying to do a batch update of records using XML:
>
> <?xml version="1.0" encoding="UTF-8"?>
> <subscribers>
> <subscriber>
>   <imei>111</imei>
>   <imsi>111</imsi>
>   <msidsm>111</msidsm>
>   <name>Six</name>
> </subscriber>
> <subscriber>
>   <imei>777</imei>
>   <imsi>777</imsi>
>   <msidsm>777</msidsm>
>   <name>Seven</name>
> </subscriber>
> </subscribers>
>
> I have this in the routes:
>
> map.resources :subscribers, :collection => {:import => :post}
>
> When I post the XML I get:
>
> Processing SubscribersController#import (for 127.0.0.1 at 2009-09-09
> 12:18:22) [POST]
>   Parameters: {"action"=>"import",
>
"subscribers"=>{"subscriber"=>[{"name"=>"Six",
"msidsm"=>"111",
> "imsi"=>"111",
"imei"=>"111"}, {"name"=>"Seven",
"msidsm"=>"777",
> "imsi"=>"777",
"imei"=>"777"}]},
"controller"=>"subscribers"}
>
> --------------------------------
>
> How can I easily create subscriber records for those I send in the XML?
> I''ve managed to extract the data but it fails when only one
subscriber
> element is included in the XML.
>
> What would be the best way to do this?
>
> Thanks.
> --
> Posted viahttp://www.ruby-forum.com/.