Putting the C in CRUD — Part 2

Group Ride App — Creating a new ride

Alison Williams
2 min readSep 30, 2021

Last week, I discussed the beginning stages of adding a user’s ability to create a ride in my Group Ride Application (read the post here). This week, I will cover the necessary work on the backend to finish creating a ride. In order to execute an asynchronous request to the Rails API backend, I employed Redux Thunk middleware. Thunk allows for returning a function inside of the action creator rather than a plain JavaScript object. The function receives the store’s dispatch function as an argument and further actions can be dispatched from inside the returned function. In this case, the function returns a fetch request with a method of POST to the API.

The request is handled by the create method in the rides controller:

def create #use the build method to add a new ride to the current user's rides
@ride = current_user.rides.build(ride_params)
#if the ride saves, send it in JSON format
if @ride.save
render json: RideSerializer.new(@ride).serializable_hash.to_json
#if the ride doesn't save, send the error messages in JSON format
else
response = {
error: @ride.errors.full_messages.to_string
}
render json: response
end
end

If no errors exist, the ride is created and saved in the database. Once the fetch request resolves and the ride is received on the frontend, an additional action creator, addRide, is dispatched to add the ride to the Redux store:

// ACTION //export const addRide = (ride) => {
return {
type: "ADD_RIDE",
ride
}
}
// REDUCER //const rideList = (state = [], action) => {
switch (action.type) {
case "GET_RIDES":
return action.rides
case "ADD_RIDE":
return state.concat(action.ride) //<-- updated//
default:
return state
}
}

A new ride is now created on both the back- and frontend of the application. Next up, I will focus on adding a React component to allow the user to view the details of their created ride as well as rides created by other users. Follow along on GitHub between blog posts.

--

--