Rails 4.2嵌套表单属性不保存

时间:2015-05-18 15:29:58

标签: ruby-on-rails nested-forms ruby-on-rails-4.2

我似乎无法获取嵌套属性来保存到数据库,尽管我可以在终端中看到params。我正在使用Rails 4.2。

以下是我的模特:

class Device < ActiveRecord::Base
    belongs_to :hub
    has_many :accessories, dependent: :destroy
    accepts_nested_attributes_for :accessories,
                         reject_if: proc { |attributes| attributes['material'].blank? },
                     allow_destroy: true
end                        

class Accessory < ActiveRecord::Base
    belongs_to :device
end

这是控制器。我的设备模型嵌套在用户和集线器模型下。

class DevicesController < ApplicationController
  def edit
    @user = User.find_by(params[:user_id])
    @hub = Hub.find_by_title(params[:hub_id])
    @device = Device.find_by(id: params[:id])

  end

  def update
    @user = User.find_by(params[:user_id])
    @hub = Hub.find_by_title(params[:hub_id])
    @device = Device.find_by(id: params[:id])

    if @device.update_attributes(device_params)
        flash[:success] = "update successfully"
        redirect_to user_hub_device_path(@user, @hub, @device)
    else
        render 'edit'
    end
  end
  private

  def device_params
    params.require(:device).permit(:model, :hub_id, :resolution, :materials, :startcost, :take_online, :delivery_time, :unitcost, :color, :accessories, :accessories_attributes => [:id, :name, :cost, :color, :device_id, :_destroy])
  end 

end

最后是我的表格。

<%= form_for([@user, @hub, @device]) do |f| %>
<fieldset>
    <div id="material">

      <%= f.fields_for :accessories do |a| %>
        <%= render 'devices/accessory', a: a %>
      <% end %>

    </div>
</fieldset>

部分:

<div class="row">
   <%= a.collection_select :name, Material.all, :material, :material  %>   
   <%= a.text_field :cost, id: "right-label" %>
   <%= a.text_field :color, id: "right-label" %>
   <%= a.check_box :_destroy %>

</div>

1 个答案:

答案 0 :(得分:0)

您将params[:device][:materials]列入白名单,但是您正在检查attributes['material'].blank?(请注意结尾处的s)。这导致嵌套属性被拒绝。