How to send json request to rails app - ruby-on-rails

I wants to send some json parameter from HTML page with text area and I want to send json parameter written in this text area eg format. {"name": "test", "description":"test", "price":100}
But rails consider it as {"{'name' : 'test', 'description' : 'test', 'price' : 100}"=>nil} how do I send json parameter from text area to be readable from rails application.

I think you need to parse that string on server side with JSON.parse
param = '{"name" : "test", "description" : "test", "price" : 100}'
# assume you got the param on server side
json_param = JSON.parse(param)
puts json_param['name']

As you stated in the comment:
You can easily understand from this sample:
<input type='textarea' name='content' value='{"name": "test", "description":"test", "price":100}' id='text_content' />
You just sent a string to Rails in this way.
If you do the submit with a form, you should use different inputs for different params.
If Javascript, maybe jQuery, you can do it with function $.post.
Rails would parse the json for you.

Related

How to Update Envelope Custom Fields of Docusign Envelope In process, with rest API in RoR

I am trying to update a Custom field in a envelope that I have already sent.
Request URL: #https://demo.docusign.net/restapi/v2/accounts/1976929/envelopes/21d46fc6-8bbe-4315-b606-47cfd0ee0e3c/custom_fields>
Request Body:
"{\"textCustomFields\": [{\"name\":\"customer_email\",\"value\":\"new_email#new.com\",\"show\":\"true\",\"required\":\"true\"}]}"
Response:
{"textCustomFields"=>
[{"fieldId"=>"10198325521", "name"=>"customer_email", "show"=>"true",
"required"=>"true", "value"=>"new_email#new.com",
"errorDetails"=>
{"errorCode"=>"CUSTOM_FIELD_ALREADY_EXISTS", "message"=>"Field Name:
customer_email"}}], "listCustomFields"=>[]}
I am trying to update the value of custom field 'Customer Email'
the response I get is Custom Field Already exist.
The use case if that if by mistake the envelope has been sent to wrong email, we'd like to update the already sent envelope with this new email and resend it.
I am on Ruby on Rails.
If initially I sent the envelope with a custom text field value old_email#email.com.
Now I would like to see the value changed to new_email#email.com
Are you using a PUT or a POST? Should be a PUT.
Also, you only need to specify "FieldId", "name", and "value".
{
"textCustomFields": [{
"fieldId": "10210399758",
"name": "customer_email",
"value": "new_email#new.com"
}]
}

ajax post to external database from Rails app

I am trying to insert data from a form built with Ruby on Rails to my SQL Server database. I have connected my database correctly and can pull data from it. I am now trying to post back to it. I am needing help with figuring out how to get the data from the form into the correct columns in my table in the database.
My ajax:
<script>
$('#Favorites').on('submit',function(event){
    var $form = $(this),
    data = $form.serialize();
    var url = 'http://localhost:3000/welcome/insert';
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function(){
            
alert('Your form has been successfully submitted!');
document.getElementById('Favorites').reset();
window.location.reload();
        },
        fail:function(){
            alert('something went wrong...try again');
        }
    });
return false;
});
</script>
My controller function:
def insert
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link)
values ('I am cool','www.google.com')")
end
Currently I just have a dummy insert statement here to make sure that I can insert into the tables and I can. I just need to know how to break out the form values sent to the controller and how to tell Rails what table and columns to put those values into.
Rails will format the data for you. In controller like this:
{'Report_Name': 'some name', 'Report_link': 'www.example.com'}
and will be accessible via the params.
Your job is now to format the data correctly for the manual execution of the SQL query.
insert_values = "('%s', '%s')" % params['Report_Name'], params['Report_link']
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link) values #{insert_values}")
For the problem of which table to add to your DB server you could specify this in hidden fields in your form and every fieled should have a name, When you say $form.serialize(); it turns it to something like FirstName=Amr&SecondName=Adel and so on where FirstName is the name of the field and Amr is the value of the field, Then you put this serialization into a form of JSON format like {"data": $form.serialize()} and add dataType: "JSON" to your post request, In your Insert function you can get it through params[:data] and split it with& to be something like ['FirstName=Amr','SecondName=Adel'] and every element split it with = so you can get something like this [['FirstName','Amr'], ['SecondName','Adel']].
Hope this helps.

json data changed in the params

This is a webhook activity I am trying do using postman. The post content is the below json.
{
"model":{
"id":"560a32d2a1dcb7902a7ad596",
"name":"cool features",
"pos":32767.5
},
"action":{
"id":"567537b94332a7d8489a0d26",
"idMemberCreator":"55024f3fdd60428e915d2c2b",
"data":{
"board":{
"shortLink":"SUDki3AR",
"name":"recipe",
"id":"560a31fad96886a87cabf39a"
},
"list":{
"name":"cool features",
"id":"560a32d2a1dcb7902a7ad596"
},
"card":{
"shortLink":"sufSA867",
"idShort":18,
"name":"added",
"id":"567537b94332a7d8489a0d25"
}
},
"type":"createCard",
"date":"2015-12-19T10:55:53.904Z",
}
}
rails strips away the action key value from params. I can only get it using request.raw_post . But it is a string . Is there a way to get the action value in the json in params? String manipulation would be very difficult.
Rails sets the params controller and action on every request, so it overwrites your action.
As you already found out, you can get the request string and as you know it's json, you can parse it (by the way: your json is invalid, an extra , after date):
action = JSON.parse(request.raw_post)['action']

How to format the date field when making a POST request to Rails API

I am adding a series of data to my rails application through a POST request to the API.
All is working well, however, whenever I try and add data to a date field, I get the following error:
> undefined method `year' for nil:NilClass
Here is an example of my JSON payload:
{
"product": {
"name": "Foo",
"start_date": "2015-11-05 22:32:03"
}
}
I know there is a potential bug with this relating to Ruby 2.2 .. however when I looked at the backend for how the params were stored on a normal create action through the frontend, they were stored a lot differently:
"start_date(1i)"=>"2020", "start_date(2i)"=>"1", "start_date(3i)"=>"1", "start_date(4i)"=>"00", "start_date(5i)"=>"01"
How would I recreate this?
It seems the backend expects to receive start date splitted by the pieces.
Please try to send data in following:
{"product":{"name": "Foo", "start_date(1i)": 2015, "start_date(2i)": 11,"start_date(3i)": 5, ...}}

How to Format to_json output to go well with update_attributes

I am working on Angular JS + Rails project . I am passing below JSON to angularJS which was created by rails to_json
user_controller.rb
render :json => current_user.to_json(:include => [:projects,:courses,:awards])
User Controller output
{"_json"=>
[{"id"=>21,
"name"=>"Demo Name",
"email"=>"demo#demo.com",
"mobile"=>"",
"dob"=>nil,
"gender"=>nil,
"address"=>nil,
"intro"=>nil,
"created_at"=>"2014-09-01T05:29:38.000Z",
"updated_at"=>"2014-09-01T05:29:38.000Z",
"projects"=>[{"id":1,"name":"Existing Project"}],
"courses"=>[],
"awards"=>[]
}]
}
Assigning data to angular $scope.userData = response._json
In Angular View , using HTML5 contenteditable (angular Directive), I am changing the value of the above object.
Angular View
<h3 ng-model="userData[0].name" contenteditable="true"></h3>
the content is changing as expected.
{"_json"=>
[{"id"=>21,
"name"=>"UPDATED NAME HERE",
"email"=>"demo#demo.com",
"mobile"=>"",
"dob"=>nil,
"gender"=>nil,
"address"=>nil,
"intro"=>nil,
"created_at"=>"2014-09-01T05:29:38.000Z",
"updated_at"=>"2014-09-01T05:29:38.000Z",
"projects"=>[{"id":1, "name":"Existing Project"},{"name":"ADDED NEW PROJECT HERE"}],
"courses"=>[{"name":"ADDED NEW COURSE HERE"}],
"awards"=>[]
}]
}
Now I need to post this object to server and update user data and all the association data like projects which has both existing and new records , what is the right way and JSON format I need to post to make this process as simple as possible.
User angular http post.
$http(
method: 'POST'
data: your_json_array_here
url: your_url_to_controller_action
).success((data,status) ->
).error((data,status) ->
)
Started using Angular Rails Resoures , also another useful references is RestAngular

Resources