gpt4 book ai didi

ruby-on-rails - Has_one 关联在编辑中被破坏

转载 作者:行者123 更新时间:2023-12-02 21:47:44 26 4
gpt4 key购买 nike

我有一个使用 cocoon gem 的嵌套表单,深度为 5 个类。它们都是belongs_to和has_many,除了具有has_one和belongs_to关联的第二个最嵌套类之外。每当我编辑它时,它都会被删除并重新创建一个实例(不是我想要的)有什么想法吗?

class FirmwaresController < ApplicationController

def index
@firmwares = Firmware.all
end

def new
@firmware = Firmware.new
end

def edit
@firmware = Firmware.find(params[:id])
end
end


class Setting < ActiveRecord::Base
belongs_to :menu_item
has_many :selections, dependent: :destroy
has_many :dependencies
attr_accessible :kind, :name, :placement, :selections_attributes
accepts_nested_attributes_for :selections, reject_if: :all_blank, allow_destroy: true
validates_presence_of :kind
end

class MenuItem < ActiveRecord::Base
belongs_to :menu
belongs_to :dependency
has_one :setting, dependent: :destroy
attr_accessible :dependency_id, :menu_for, :name, :placement, :setting_attributes
accepts_nested_attributes_for :setting, reject_if: :all_blank, allow_destroy: true
validates_presence_of :name

end

_menu_items.html.haml

.row-fluid
.input-prepend
= f.input :name, label: "Menu Item Name"
.input-append
= f.input :placement, label: "Order in Menu (X.Y)", as: :string
= f.simple_fields_for :setting do |settings_form|
= render 'setting_fields', f: settings_form
%p
= link_to_add_association "Has Setting?", f, :setting, class: "btn btn-primary btn-small add_setting_link"
= link_to_remove_association 'Remove Menu Item', f, class: "btn btn-danger btn-small remove_menu_item"

_setting_fields.html.haml

.row-fluid
.input-prepend
= f.input :kind, label: "Type", collection: setting_kinds, input_html: {class: "setting_type"}
.input-append
= link_to_remove_association 'Remove Setting', f, class: 'btn btn-danger btn-small remove_setting_link'
.setting_selection{style: "display: none;"}
= f.simple_fields_for :selections do |selections_form|
= render 'selection_fields', f: selections_form
%p= link_to_add_association 'Add Selection Option', f, :selections, class: "btn btn-primary btn-small"

最佳答案

我假设您引用的 has_one 关联是 MenuItem 中的 has_one :setting。如果是这样,您可以尝试将 update_only: true 添加到您的 accepts_nested_attributes_for :setting 选项中。 From the documentation (强调我的):

By default the :update_only option is false and the nested attributes are used to update the existing record only if they include the record's :id value. Otherwise a new record will be instantiated and used to replace the existing one. However if the :update_only option is true, the nested attributes are used to update the record’s attributes always, regardless of whether the :id is present.

关于ruby-on-rails - Has_one 关联在编辑中被破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19229287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com