【问题标题】:Updating an existing value with the update action will cause a new one to be added使用更新操作更新现有值将导致添加新值
【发布时间】:2021-09-09 13:35:27
【问题描述】:

我想要实现的目标

如果您使用更新操作进行更新,则将添加新值而不更改原始值。我希望反映编辑的值。 我将 Rails 用于服务器,将 Nuxt 用于视图。 顺便说一句,没有错误。 例如,如果您尝试将“Test”的值更改为“Test2”的值,您会看到除了“Test”的值之外,“Test2”的值还会添加到“Test”的值中。我想把“Test”改成“Test2”。

代码

导轨 控制器

class Api::V1::PostsController < ApplicationController
    def index
        posts = Post.all
        render json: posts
    end

    def create
        posts = Post.new(create_params)
        if posts.save
            render json: posts, status: :created
        else
            ender json: { errors: post.errors.full_messages },  status: :internal_server_error
        end
    end

    def show
        content = post.post_items
        render json: {"post": post, "content": content}, status: :ok
    end
//////////////////////////////////////////////////////////////////////////////
//Target
// I using accepts_nested_attributes_for.
     
     def update
        if post.update(update_params)
            head :ok 
        else
            render json: { errors: post.errors.full_messages }, status: :internal_server_error
        end
     end
     
//////////////////////////////////////////////////////////////////////////////////
     def destroy
    if  post.destroy
         render json: {}, status: :ok
        else
        render json: {}, status: :internal_server_error
        end
     end

        private
        def post 
            @post ||= Post.find(params[:id])
        end 

        def post_item_params
          [:id, :content, :status]
        end

         def update_params
             params.require(:post).permit(post_items_attributes: post_item_params)
         end


         def create_params
             params.require(:post).permit(:title, :author, :image, post_items_attributes: post_item_params)
         end
end

型号

class Post < ApplicationRecord
    has_many :post_items, dependent: :destroy
    accepts_nested_attributes_for :post_items, allow_destroy: true

    validates :title, presence: true
    validates :author, presence: true
    validates :image, presence: true
end

Nuxt 商店


  update (context) {
    const list = context.state.todos.list
    const selectedBook = context.state.book.selectedBook
    const postItemsAttributes =
    list.map((item) => {
      return {
        id: item.id,
        content: item.content,
        status: false
      }
    })
    this.$axios.$patch(url.POST_API + 'posts/' + selectedBook.id, {
      post: {
        post_items_attributes: postItemsAttributes
      }
    })
  }

商店/待办事项

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

export const mutations = {

  add (state, content) {
    state.list.push({
      content,
      status: false
    })
  },


  remove (state, todo) {
    state.list.splice(state.list.indexOf(todo), 1)
  },

/////////////////////////////////////////////////////////////////////
//Add the edited values to the list; generate values to be used in update

  edit (state, { todo, content }) {
    state.list.splice(state.list.indexOf(todo), 1, { content })
  }
/////////////////////////////////////////////////////////////////////

我的假设是,如果我更改了 todos.list 中的值并将其发送到服务器,数据库将用该值替换它。

参数

创建

pi_1    |   Post Create (5.6ms)  INSERT INTO "posts" ("title", "author", "image", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["title", "Test Your English"], ["author", "Muhammad Ali Alkhuli"], ["image", "http://books.google.com/books/content?id=gfefAQAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"], ["created_at", "2021-09-10 01:19:56.889536"], ["updated_at", "2021-09-10 01:19:56.889536"]]
api_1    |   ↳ app/controllers/api/v1/posts_controller.rb:9:in `create'
api_1    |   PostItem Create (4.1ms)  INSERT INTO "post_items" ("content", "post_id", "created_at", "updated_at", "status") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["content", "Test"], ["post_id", 12], ["created_at", "2021-09-10 01:19:56.931199"], ["updated_at", "2021-09-10 01:19:56.931199"], ["status", false]]
api_1    |   ↳ app/controllers/api/v1/posts_controller.rb:9:in `create'
api_1    |    (8.7ms)  COMMIT
api_1    |   ↳ app/controllers/api/v1/posts_controller.rb:9:in `create'
api_1    | [active_model_serializers] Rendered PostSerializer with ActiveModelSerializers::Adapter::Attributes (2.86ms)
api_1    | Completed 201 Created in 84ms (Views: 7.3ms | ActiveRecord: 19.3ms | Allocations: 4437)

更新

api_1    |   PostItem Create (10.2ms)  INSERT INTO "post_items" ("content", "post_id", "created_at", "updated_at", "status") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["content", "Test2"], ["post_id", 12], ["created_at", "2021-09-10 01:27:20.789174"], ["updated_at", "2021-09-10 01:27:20.789174"], ["status", false]]
api_1    |   ↳ app/controllers/api/v1/posts_controller.rb:22:in `update'
api_1    |    (12.3ms)  COMMIT
api_1    |   ↳ app/controllers/api/v1/posts_controller.rb:22:in `update'
api_1    | Completed 200 OK in 164ms (ActiveRecord: 87.4ms | Allocations: 4321)

【问题讨论】:

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


    【解决方案1】:

    如果你想在编辑后创建一个新模型,那么 update 不是合适的 http 动词,它应该是 post。由于您正在编辑现有模型,它已经有一个 id,但您希望创建一个新模型,您必须删除该 id,以便 Rails 了解它尚未持久化。

    有意义吗?

    【讨论】:

    • 这是否意味着无法使用更新来更改值?我只想使用 update 来编辑 post_items 的值。
    • 是的,您可以使用 update 更改值,这是合适的。但是如果我理解正确你想使用更新创建一个新模型,我误解了吗?要创建,它应该是发布/创建而不是补丁/更新。
    • 对不起,我的解释有误导性。我想更新post_items的值,但是当我运行更新时,值被添加了,原来的值没有改变。
    • 请在提交更新时显示 PostsController#update 方法收到的 params 哈希。
    • 好吧,您没有向我们展示参数,只是显示从参数生成的 sql 的日志,我正在寻找 update_params 哈希变量的值。但是您观察到 post_items 的 ID 缺失是您观察到的行为最可能的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多