###前提・実現したいこと
RailsのMVCのフレームワークで開発していて、Viewの部分をReactで書こうとしています。
react_componentでの関連モデルの渡し方に疑問があります。
###ソースコード
Modelファイル
ruby
1class Article < ApplicationRecord 2 has_many :article_tags 3 has_many :tags, through: :article_tags 4end
ruby
1class Tag < ApplicationRecord 2 has_many :article_tags 3 has_many :articles,through: :article_tags 4end
ruby
1class ArticleTag < ApplicationRecord 2 belongs_to :article 3 belongs_to :tag 4end
Viewファイル
html
1<%= react_component('ArticleList', 2 data: @articles 3 ) %>
Controllerファイル
ruby
1class ArticlesController < ApplicationController 2 def index 3 @articles = Article.all 4 end 5end
###発生している問題
Viewファイル内のreact_componentメソッドでdata:@articlesという形で引数をjsに渡したときに、articlesに関連づけてあるtagsが渡されません。
articles[0].tags
のような形でタグを取り出したいです。
###試したこと
https://stackoverflow.com/questions/33229296/how-does-reactjs-handles-rails-active-record-associations
を参考に、Controllerファイルでのモデル呼び出しの記述を
ruby
1@articles = Article.all.includes(:tags).as_json(include: { tags: { only: [:tag_name] } })
に変更したらうまくいきました。しかし、コントローラーを書き換えないといけないとなるとサーバーサイドの負担が増えますし、railsの強みを消している気がします。View側だけで完結する良い方法はありますでしょうか?
あなたの回答
tips
プレビュー