Posting a json array to rails server - ruby-on-rails

I want to know how can I post json array directly to rails server. Say,
POST '/api/notes_bulk', HTTP/1.1
Content-Type: application/json
[{“content”:”content1”, “title”:”title1”}, {“content”:”content2”, “title”:”title2”}, {“content”:”content3”, “title”:”title3”}, {“content”:”content4”, “title”:”title4”}, {“content”:”content5”, “title”:”title5”}]
I did some search about it and all of the examples had some kind of key mapped to the array. While in my case, the json is an array at its top level.
How can I get the json data in the controller code? I notice that rails wraps this data with a "_json" key, but when I accessing it, it says
Unpermitted parameters: _json, ....

You can use that '_json' key to access data. To remove the warning you have to permit all the object keys from JSON array. In your case:
params.permit(_json: [:content, :title])

You cannot use the built-in params from Rails in this case but you can create your own parser:
def create
contents = JSON.parse(request.raw_post)
end
The contents variable will be the array that you posted.

i think the issue you are facing had got to do with strong parameters.
you need to allow json params in controller.
Use params.require(:object).permit( list of allowed params)

I think this might be late, but just post here since the question is unanswered and for future visitors.
You have to wrap you JSON string into an object. For example, you can construct you Json string such as
var contentArray = [{“content”:”content1”, “title”:”title1”}, {“content”:”content2”, “title”:”title2”}];
var contentObj = {contents: contentArray};
Before submiting it to Rails
jsonData = JSON.stringify(contentObj);
Access it in Rails controller:
myContentArray = params[:contents]

Related

Adding default field such as timestamp to json when rendering in rails

I am newbie in Ruby on rails and want to config render :json, always adds an extra field such as timestamp or version at the end of json response. Like this
{
//json data
"time_stamp" : 24312512341235
}
I think it might have better way to do that than adding parameter everytime calling render json
Thanks for helping
Just like html, you can have a layout for JSON responses.
Create a file app/views/layouts/application.json.jbuilder
and fill it with this:
json.merge! JSON.parse(yield)
json.time_stamp Time.now.to_i
Note that you need to make sure you always return a JSON Object and not an Array.

Saving data from a JSON response

I currently have a JSON response, fairly simple one. But I couldn't find a good guide or kicking off point for getting the JSON response and saving it within a model that I have e.g posts.
"Grab a JSON feed containing posts and save each one within the posts
table in rails"
Is there a simple way to do this with rails?
Any help is greatly appreciated.
Not a lot to work with...but let's assume the json string is represented by the variable json_str.
parsed = JSON.parse(json_str)
The parsed string should now essentially just be key value pairs like any other hash. To get the value, simply use the key.
parsed["some_key"]
Will return the value. To make your post from this, you can take the values you need and pass them in one by one, like so:
Post.create(some_value: parsed["some_key"], # etc)
Or, if all of your keys happen to share names with your attributes, you can pass the params all at once by saying:
post = Post.new(parsed)
and then calling:
post.save
Let me know if you have trouble.

Saving Mutiple arrays with strong parameters Ruby on Rails 4

I have an ajax response like this ,
google_searched_locations [{"geometry":{"location":{"J":31.482273,"M":74.33069999999998}},"icon":"https://maps.gstatic.com/mapfiles
/place_api/icons/restaurant-71.png","id":"b93a99a46343de01d0d928f99470f9b0f5f6f11d","name":"Dunkin' Donuts"
,"place_id":"ChIJSeoh6hkEGTkRsd0e1crAbHU","rating":4.3,"reference":"CnRhAAAAewgE30hrAcax1xdGPIf7M863
bOtNhRgfnncMx17uWMgtdTyGHGbTO76LX6yXsPyB4PcvfVzIeeIR1bxG0oSambqMYxFWwqHY3Cyfs6uWFp2QbVkGObvQ1LlTrdqLh1eZVgX8aL0iRFFhAnHEM8u1RxIQACDCn2BMD3IiG7tKri31BRoULMSagTU-EmxswgLxzCOWPVVnlpI"
,"scope":"GOOGLE","types":["restaurant","food","point_of_interest","establishment"],"vicinity":"Lahore"
,"html_attributions":[]}]
After JSON.parse(thisString) , I get the required result by using params["places"][0]["geometry"] and then looping over it , but I know that it's not a better way when Rails have strong parameter there , so I tried some solutions after searching , below is my strong parameters function
def google_places
json_params = ActionController::Parameters.new(JSON.parse(request.body.read) )
json_params.require(:google_searched_locations).permit(:icon)
end
but it gives the following error ,
JSON::ParserError in SearchesController#searchResults
757: unexpected token at 'places=%5B%7B%22geometry
Can anyone make us out of this mess , and tell us what's happening here and where is the right way to go .
Thanks in advance :)
You do not need to manually parse JSON parameters. Rails will automatically parse the parameters provided the request has the correct format (more specifically the correct mime type headers). In fact doing so will be slower and use more memory since you are doing the same parsing work twice.
To allow an array of parameters you simply use the hash key and an array of the permitted attributes for the nested params.
def google_places
params.permit(places: [:icon, { location: [:H, :L] }])
end
If possible you should change the H and L parameters to lowercase so that you can map them directly to attributes without violating the ruby conventions of lowercase attributes.

Rails: Converting URL strings to params?

I know Rails does this for you, but I have a need to do this myself for examples. Is there a simple, non-private method available that takes a string and returns the hash of params exactly as Rails does for controllers?
Using Rack::Utils.parse_nested_query(some_string) will give you better results since CGI will convert all the values to arrays.
I found a way after a more intense Google search.
To convert url string to params:
hash = CGI::parse(some_string)
And (as bonus) from hash back to url string:
some_string = hash.to_query
Thanks to: https://www.ruby-forum.com/topic/69428
In model you can write a query like
def to_param
"-#{self.first_name}" +"-"+ "#{self.last_name}"
end
More info
http://apidock.com/rails/ActiveRecord/Base/to_param
It will generate a url like http://ul.com/12-Ravin-Drope
More firendly url you can consult
https://gist.github.com/cdmwebs/1209732

Ruby getting deeply nested JSON API data

I have a rails app which gets a response from World Weather Online API. I'm using the rest-client gem and the response is in JSON format.
I parse the response using:
parsed_response = JSON.parse(response)
Where parsed_response is obviously a hash.
The data I need are strings inside a hash inside an array inside a hash inside another array inside another hash inside another hash.
The inner-most nested hashes are inside ["hourly"], an array of 8 hashes, each with 20 keys, possessing string values of various weather parameters. Each of these hashes in the array is a different time of day (the forecast is three-hourly, 3*8 = 24hours).
So, for example, if I want the swell height in metres at 9pm, I find it with the following call:
#swell_height = parsed_data["data"]["weather"][0]["hourly"][7]["swellHeight_m"]
Where the 7th element in the array correspond to "time" => "2100"
While I can definitely work with this, I'm curious as to whether there is a more straightforward method of accessing my data, like if it was a database table, I could use active record, something like:
#swell_height = parsed_data.swellHeight_m.where(:time => "2100")
You may want to look at JSONPath. It does exactly what you need. Its syntax is very similar to XPath, but JSONPath works with JSON data (as obvious).
There is a Ruby implementation: https://github.com/joshbuddy/jsonpath
I personally use it in every project where I need to test JSON responses.

Resources