Rails accepts_nested_attributes_for始终创建嵌套模型,但不更新它们 [英] Rails accepts_nested_attributes_for always creates the nested models, but does not update them

查看:66
本文介绍了Rails accepts_nested_attributes_for始终创建嵌套模型,但不更新它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下内容:

class WebsitesController < ApplicationController
  # POST /websites/save
  # POST /websites/save.json
  def save
    Website.exists?(name: params[:website][:name]) ? update : create
  end

  # POST /websites
  # POST /websites.json
  def create
    @server  = Server.find_or_create_by_name(params[:server_id])
    @website = @server.websites.new(params[:website])

    #etc... @website.save
  end

  # PUT /websites/1
  # PUT /websites/1.json
  def update
    @website = Website.find_by_name(params[:website][:name])

    #etc... @website.update_attributes
  end
end



客户端没有这些模型的任何ID



发送的请求仅具有名称,但不是 id

以及以下型号

class Website < ActiveRecord::Base
  serialize :website_errors

  attr_accessible :plugins_attributes
  has_many :plugins

  accepts_nested_attributes_for :plugins
end

class Plugin < ActiveRecord::Base
  belongs_to :website
end

当我创建 POST 请求发送到 /websites/save.json 网站可以正确更新(如果存在),但是始终会重新创建属于它的插件,从而导致数据库中的重复内容。为什么会这样?我重定向到 update 动作,该动作调用 update_attributes ,所以怎么可能不更新呢?我认为这是因为请求没有给出ID。

When I make a POST request to /websites/save.json, the Website gets updated correctly if it exists, but the Plugins that belong to it always get recreated causing duplicate content in the Database. Why does this happen? I redirect to the update action which calls update_attributes so how can it be that it does not update it? I take it that it's because no ID is given with the request.

我可以让 Controller 监听 plugin_name 而不是 plugin_id

推荐答案

修改您的控制器使其具有:

Modify your controller to have this:

def update
  @website = Website.find_by_name(params[:website][:name])
  if @website.update(params)
    redirect_to website_path(@website)
  else
    render :edit
  end
end

此外,如果您使用的是 strong_parameters ,则需要在控制器的底部:

Also, if you're using strong_parameters, you'll need this at the bottom of your controller:

params.require(:website).
  permit(
    :name,
    ...,
    plugins_attributes: [
      :name,
      ...,
    ]
  )
end

这篇关于Rails accepts_nested_attributes_for始终创建嵌套模型,但不更新它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆