编辑中的Has_one关联中断

时间:2013-10-07 15:56:26

标签: ruby-on-rails ruby-on-rails-3.2 associations nested-forms cocoon-gem

我有一个使用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"

2 个答案:

答案 0 :(得分:3)

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

  

默认情况下,:update_only选项为false,嵌套属性仅在包含记录的:id值时才用于更新现有记录。 否则将实例化新记录并用于替换现有记录。但是,如果:update_only选项为true,则嵌套属性将始终用于更新记录的属性,无论是否:id存在。

答案 1 :(得分:2)

这个问题很老,但这可以帮助一些人:

我总是为我重新创建关联的原因是,我忘记在:id的允许参数中包含phone_number_attributes!如果你忘记这样做,rails将不会获得id,并将重新创建一个新记录来替换旧记录。

def user_params
  params.require(:user).permit(
    :avatar,
    :remove_avatar,
    { id_photo_attributes: [:photo, :remove_photo] },
    { phone_number_attributes: [:id, :phone_number] } # dont forget :id here!
  )
end
相关问题