johnnycakes
johnnycakes

Reputation: 2450

Ruby/Rails - Can't access JSON object attributes directly in controller

I am setting up an API.

The client (using HTTParty) posts this to the API:

{:body => 
       {
        :product=> {:description=>"some text", :cost => "11.99"}, 
        :brand=>   {:name=>"BrandName", :etc =>"hey"}
       }
}

The server/api receives the post. Now, if I access params[:brand] I get:

{"name"=>"BrandName", "etc" =>"hey"}

If I do this:

Brand.new(params[:brand])

Then I get a new Brand object with the "name" and "etc" attributes populated correctly.

However, if I try to access params[:brand][:name], I just get nil

Any ideas?

Thanks.

Upvotes: 2

Views: 2944

Answers (1)

tybro0103
tybro0103

Reputation: 49693

Use params[:brand]["name"] or params["brand"]["name"]

Hash keys can be any sort of object. Common rails practice is to use symbols as hash keys, but when translated from JSON, the keys are likely to be strings.

Upvotes: 3

Related Questions