uno
uno

Reputation: 1481

Saving json response in create

I want to save a json response but it is saving the title instead of the value. Also having issues with how the params are coming through with slashes instead of as a hash

I have the following response from form submit:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"2134", "shipping_rate"=>{..."shipping_rate"=>"{\"serviceName\"=>\"USPS First Class Mail - Package\", \"serviceCode\"=>\"usps_first_class_mail\", \"shipmentCost\"=>2.66, \"otherCost\"=>0.0}"}, "commit"=>"Create Shipping rate"}

form:

...
<% @rates.each do |rate| %>
  <%= form.radio_button :shipping_rate, rate.as_json %> <%= rate %><br />
<% end %>
...

I am under the impression using as_json removes the "/" so it comes through as a hash parameters.

I also tried using @rates.as_json.each with same results

Create method in controller:

@shipping_rate.service_code = params["shipping_rate"]["shipping_rate"]["serviceCode"]

How the service_code saves is as "serviceCode" and not "usps_first_class_mail".

How can I:

  1. Have the params come through as a hash, without the /'s
  2. Save the value of params["shipping_rate"]["shipping_rate"]["serviceCode"] instead of the title

Upvotes: 0

Views: 89

Answers (1)

Glyoko
Glyoko

Reputation: 2080

rate.as_json is correctly returning a hash, but when you pass data to form.radio_button it get's converted into something html friendly. Basically, form.radio_button calls .to_s (or some similar method that probably also escapes html) on that hash, which is why you're getting the hash as a string.

As a rule, individual HTML form elements should not contain hash data, and especially not ruby formatted hash data. Keep in mind that once the page is rendered in a browser, it knows nothing about the backend, let alone how to run ruby code.

You should take a step back and think of this RESTfully. If your users are meant to select a rate, and you have a number of rate records in your db, you really only need them to send back the id of the rate they would like. Without seeing your controller it's hard to tell exactly what else would need to change, but your radio buttons should probably look more like:

<%= form.radio_button :rate_id, rate.id %>

Your controller's create method would then be responsible for setting the user's selected rate, possibly requiring you to look up the rate again.

Upvotes: 0

Related Questions