Rails初心者です。
Rails5でウェブアプリの開発をしています。
class Post < ApplicationRecord has_many :comments end class Comment < ApplicationRecord belongs_to :post end
上記のような関連のある状態で、DBから取得したデータをJSで扱いたいと思っております。
ruby
1@posts = Post.includes(:comments).all
html
1<div id="posts" data-posts="<%= @posts.to_json %>"></div>
Viewで @posts
をループさせて comments
を表示させることは問題なくできるのですが、上記のようにしてそのままJSに渡しても、 comments
の含まれないオブジェクトとして渡ってきます。
coffeescript
1$ -> 2 console.log $('#posts').data() 3 4 # こうなる 5 # posts: [ 6 # { 7 # title: xxx, 8 # body: xxx 9 # }, 10 # ... 11 # ] 12 13 # こうなって欲しい 14 # posts: [ 15 # { 16 # title: xxx, 17 # body: xxx, 18 # comments: [ 19 # { body: xxx, user_id: xxx }, 20 # ... 21 # ] 22 # }, 23 # ... 24 # ]
この挙動はRailsの普通の挙動ですか?
またこのような場合、別々の配列としてJSに渡し、JS側で構造を整えるしか方法はありませんか?
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。