I want to send the value of an object to the server

What I want to come true

I am creating an app. View is Nuxt and server is Rails. I can’t register the text as I want.

I am registering book information. There are multiple pieces of information that I want to register, and the content and status of post_items_attributes are multiple, but only one can be registered. What should I do in this case? If you set it to 0, you can only register one, so I don’t know what to do.

    this.$axios.$post(url.POST_API + 'posts', {
      post: {
        title: this.$title(selectedBook),
        author: this.$author(selectedBook),
        image: this.$image(selectedBook),
        post_items_attributes: [{
/////////////////////////////////////////////////
          content: list[0].content, 
          status: list[0].status
////////////////////////////////////////////////
        }]
      }
    })
      .then((responseBook) => {
        context.commit('book/userBook', responseBook)
        context.commit('book/clearBook')
        context.commit('todos/clear')
      })
  },

this.$store.state.todos.list

export const state = () => ({
  list: []
})

enter image description here

In list

Code

Nuxt

    const list = context.state.todos.list
    const selectedBook = context.state.book.selectedBook

    // plugin/bookInfo  $title,$author,$image
    this.$axios.$post(url.POST_API + 'posts', {

    // send to Rails
      post: {
        title: this.$title(selectedBook),
        author: this.$author(selectedBook),
        image: this.$image(selectedBook),
        post_items_attributes: [{
/////////////////////////////////////////////////////////////
          content: list[0].content,
          status: list[0].status
////////////////////////////////////////////////////////////
        }]
      }
    })
      .then((responseBook) => {
        context.commit('book/userBook', responseBook)
        context.commit('book/clearBook')
        context.commit('todos/clear')
      })
  },

Rails

    def create
        posts = Post.new(post_params)
        if posts.save
            render json: 'OK', status: 200
        else
            render json: 'EEEOR', status: 500
        end
    end

        private
         def post_params
            params.require(:post).permit(:title, :author, :image, post_items_attributes: [:id, :content, :status])
         end



Answer

You don’t give example of list in the question code. But from the context, I conclude that this is an array of JS objects. So you can map it like this:

let post_items_attributes =
  list.map(item => {
    return {
      content: item.content,
      status: item.status,
    }
  })

And then pass it in the post:

post: {
  title: this.$title(selectedBook),
  author: this.$author(selectedBook),
  image: this.$image(selectedBook),
  post_items_attributes: post_items_attributes
}

Or you can do it inline without this variable