React Js And Rails Updating State On A Component With Active Record Relationship

- 1 answer

I am having issues updating a component in react with rails in the backend. I understand what the issue is but I do not know how to fix it. I will try to explain but before here some of my code, So my controller I am passing the data like this:

def index
  @vehicles = Vehicle.all.includes(:customer).as_json(include: {customer: 
  { only: [:name, :lastname, :id]}})
  @customers = Customer.all
  @years =

Vehicle belongs to customer and I am passing the customer data along. However because I am also creating new instances of vehicles I need to pass the Customer data completely so that I can get all the customers listed to pick from. I am going to try to explain rather than putting all of react code since is too verbose. Vehicle state is an Object that contains customer inside like this

{key1:value,...{customer:{name:value, lastname:value, id:value}, customer_id:value}

When I enter a new vehicle I use a select box to get the customer and select box name is customer_id which is the foreign key, this goes into an Ajax and updates the server just fine. The problem is that since I am only passing customer_id while is enough for the server to update is not enough for react the way react is set up is that after the ajax the object is push into the collection array on the client side and react just render that array into the index immediately. When react attempt to update the state i get this on the console.

Uncaught TypeError: Cannot read property 'name' of undefined

This happens because the object that am sending in the ajax call does not includes the customer name or last name only the foreign key. The only way to see the new state is to refresh the page as new Vehicle is rendered and it comes from the server correctly. Will I have to create a different object to update the state on the front end?



The miss in this area was on the backend not the front end. Rails create method was not passing the object serialized so that react can include the customer information. What I proceeded to do was to create a serialiser:

      class VehicleSerializer

       def initialize(vehicle)
         @vehicle = vehicle

      def attributes
           customer: {
               lastname: @vehicle.customer.lastname,
             plate: @vehicle.plate,
             year: @vehicle.year,
             make: @vehicle.make,
             model: @vehicle.model,
             engine: @vehicle.engine,
             basevehicleid: @vehicle.basevehicleid

Then I used that in the vehicle controller create method like this:

    def create
       @vehicle =

         render json:
     render json: @vehicle.errors, status: :unprocessable_entity

That fixed the problem so that react could have the information completed. the reason that was being fix by re-rendering was because when you hit refresh is the index action the method being used and that was already serialized.