I'm doing some project using Ruby on Rails with React. I'm using react-rails
gem. I have some questions about how to properly design the architecture of Rails and React app. My question is mainly about passing data between Rails and React.
I know there are mainly two approaches to this. First and most common way is separate API in Rails and frontend app in React. This brings some pros and cons. I'd have to develop and maintain two separate apps but in the future, I could easily reuse existing API to other things like a mobile app. In this way, my frontend React ask Rails API for data.
The second way and way I chose is to develop monolith app using built-in in Rails webpacker
, react-rails
or react-on-rails
. In this way, I can simply fetch data in my Rails controller
@foo = Model.find(id)
and pass it to my React component in view
=react_component("Foo", {foo: @foo})
but the problem started when I have got some more complex model with more dependencies. For example, let say I have a model:
class Foo < ApplicationRecord
belongs_to: :user
has_many: :bar #which is some nested resources
and now I want to create an index page of model Foo
which will display all Foo's
, user
data and connected to it Bar's
. In pure Rails app, i can simply ask in the controller for @foo
and later in view just use @foo.user.nick
. But when I'm using react I need to have all this information fetched in my controller an then passed to React component using props
which cause in my opinion a lot of mess.
And here is my question: What is a proper way for passing data between Rails and React?
The cleanest option is as you say to fetch in the controller and pass in using props.
If you're doing it as props, the best way is to leverage Rails's as_json
method with it's chainable options of:
And an example:
@my_component_data = @foo.as_json(include: { user: { only: [:id, :name, :nick] } }
Eventually you may choose something like ActiveModelSerializers but I personally prefer to avoid the speed loss and added complexity, others swear by it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.