简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM