dt1000
dt1000

Reputation: 3732

Rails 3 deserialize array

This is my first time serializing. I serialized an array of checkboxes w/ jQuery on the client side, put it into a hidden element, and submitted the form. Now on the server side I want to deserialize into an array I can use. Here is my string on the client side.

 someArray%5B%5D=value0&someArray%5B%5D=value1

In Rails 3, I would like to get an array that looks like:

["value0", "value1"]

Thanks!

Upvotes: 1

Views: 669

Answers (2)

damuz91
damuz91

Reputation: 1728

For serialization i came up with something and i've got working in production for a while. Lets say i've got a Car model with 3 different type of gadgets. (Lets assume i dont want 3 fields in DB):

in your database must be a field named gadgets as TEXT (ths is very important)

in Car.rb

serialize :gadgets
attr_accessible :alarm, :ac, :tires
ALARM = 0;
AC = 1;
TIRES = 2;

# this is the getter for alarm
def has_alarm
  if self.gadgets.nil?
    return 0
  else
    if self.gadgets[ALARM].nil?
      return 0
    else
      return self.gadgets[ALARM]
    end
end

# this is the setter for alarm
def has_alarm=(value)
  self.gadgets = Array.new if self.gadgets.nil?
  self.gadgets[ALARM] = value
end

# getter 
def has_ac
  if self.gadgets.nil?
    return 0
  else
    if self.gadgets[AC].nil?
      return 0
    else
      return self.gadgets[AC]
    end
end

# setter
def has_ac=(value)
  self.gadgets = Array.new if self.gadgets.nil?
  self.gadgets[AC] = value
end

...

in your _form.rb

<%= f.check_box :has_alarm %> I want alarm in my car
<%= f.check_box :has_ac %> I want AC in my car
<%= f.check_box :has_tires %> I want deluxe tires in my car

I hope you dont have to search by these fields later...

Upvotes: 1

Ryan Bigg
Ryan Bigg

Reputation: 107718

Rack will automatically parse these values if you submit them as typical post parameters to your request. For example:

curl http://yoursite.com -d "array[]=somevalue&array[]=othervalue"

This will then be available as params[:array] within your application, containing two elements with the values specified.

Upvotes: 2

Related Questions