Home » vue » Include comments with post in rails

Include comments with post in rails

Posted by: admin November 26, 2021 Leave a comment

Questions:

Im building a rails app with vue components on several pages. I pass my data to the vue component like so:

<v-my-component :posts="<%= @post.to_json %>"></v-my-component>

This works fine and I get my posts as json passed as a prop to my component. However if I want to also include the post comments, how could I do this? I want something like:

#posts/show
<v-my-component :posts="<%= @post.wtih(:comment).to_json %>"></v-my-component>

my json should look something like:

post
    title:"",
    body:"",
    ...,
    comments:[
        {
            id:1,
            comment_body:"",
            ...
        },
        ...
    ]

Does anyone know how to achieve this? Thanks in advance

Answers:

You need to pass the option to to_json:

<v-my-component :posts="<%= @post.to_json(include: :comments) %>"></v-my-component>