Using javascript to create an object in a rails API

Triston Herbst
2 min readApr 27, 2021

To create an object in a rails API using javascript in the frontend we first need to set up our backend. Make sure you have your controller setup(also your models, tables, database …etc) so that it has the ability to create it on the rails side(make sure you are permitting the values you need). In your controller be sure to add ‘render json: example’ if you want to get the new object you created back in the response.

So when its time to actually create the object in javascript you need to have your fetch with the method ‘POST’. In my example my team and I were creating a new ingredient object with the keys, name and basket_id, then passing that in the body.

In our case we did not need to do anything with each specific ingredient so we didn’t need to get it back from the response but the code below will show you how to do that. All you need are two then statements and the second one will give you your new object.

--

--