Search code examples
ruby-on-railsrubydecoratoractive-model-serializersreact-rails

How to build a view object in Rails for JavaScript use


What I'm trying to achieve is to use a decorator (maybe Draper) to build an object before passing it to my React code (using the React Rails gem). I can easily decorate an object and use the methods in a view, but that is not possible if I pass an array through React props:

<%= react_component('Project', { name: project.name, choices: project.options %>

I won't be able access the decorated project.options.total method in my JavaScript code.

Is there another way of building these objects? I was using Active Model Serializers in the past, but this is not a single page app, it's just a React component inside a Rails view.


Solution

  • A solution would be to create a method that adds the required fields to to a JSON string before it gets passed to the React component.

    I think I managed to find a cleaner solution by using Active Model Serializers. You create a serializer and build the JSON in your controller method:

    @project_json = ActiveModelSerializers::SerializableResource.new(@projects).as_json
    

    As a side note, adding the current_user to that serializer can be easily done by using a scope:

    ActiveModelSerializers::SerializableResource.new(@projects, scope: current_user, scope_name: :current_user).as_json