【问题标题】:I want to send the value of an object to the server我想将对象的值发送到服务器
【发布时间】:2021-08-31 04:32:11
【问题描述】:

我想要实现的目标

我正在创建一个应用程序。视图是 Nuxt,服务器是 Rails。 我无法随意注册文本。

我正在注册图书信息。 我要注册的信息有多个,post_items_attributes的内容和状态有多个,但是只能注册一个。在这种情况下我该怎么办? 如果设置为0,只能注册一个,不知道怎么办。

    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: []
})

在列表中

代码

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')
      })
  },

导轨

    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



【问题讨论】:

    标签: javascript ruby-on-rails vue.js nuxt.js


    【解决方案1】:

    您没有在问题代码中给出list 的示例。但是从上下文来看,我断定这是一个 JS 对象数组。所以你可以像这样映射它:

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

    然后传入post:

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

    或者你可以在没有这个变量的情况下内联

    【讨论】:

    • 感谢您的评论。以前,向 Rails 发送值需要“[]”。为什么在创建 post_items_attributes 后不再需要“[]”?
    • 如果list 是空数组,post_items_attributes 也将是空数组
    猜你喜欢
    • 2017-02-24
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多