存在简单字段保存问题

时间:2015-08-03 11:30:40

标签: ruby-on-rails mongoid simple-form

我遇到表单问题,简单字段不保存在数组选项中

Product.rb

   class Product
      include Mongoid::Document
      field :name, type: String
      field :options, type: Array 
      field :active, type: Boolean
      field :main, type: Boolean
      field :category, type: String
    end

_form.html.haml

= simple_form_for [:admin, @product] do |f|
  = f.error_notification
  .form-inputs
    = f.input :name
    = f.input :main
    = f.input :category
    = f.input :active
    = f.simple_fields_for :options do |ff|
      = ff.input :mass
      = ff.input :volume
      = ff.input :price
      = ff.input :amount
      = ff.input :packing
  .form-actions
    = f.button :submit

product_controller.rb

    def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to [:admin, @product], notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end
    def product_params
    params.require(:product).permit(:name, :active, :main, :category, :options )
    end

保存产品名称,但选项为nill。 @product [:options]`是nil

问题是我有很多已经在种子的基础上工作。在种子选项中列为数组,而不是类。为此,有必要在不使用class选项的情况下找到出路。

1 个答案:

答案 0 :(得分:1)

对象类型

:options这里不是一个简单的字段。您希望它是键/值对的嵌套哈希,

options = {
  'mass' => '45kg',
  'volume' => '35L'
}

或者如果你想保留数组结构,它应该是一个数组数组,如

options = [ ['mass', '35kg'], ['volume', '35L'],...]

或展平

options = [ 'mass', '35kg', 'volume', '35L',...]

或散列数组

options = [ {'mass': '35kg'}, {'volume': '35L'} ,...]

许可方法

rails is very particular and misleading中的语法。简而言之

params.require(:product).permit(
  :name, 
  :active, 
  :main, 
  :category, 
  # Array of strings
  # => { options: ['mass', '35kg', 'amount', ...]}
  { options: [] },

  # Array of hashes 
  # => { options: [ {mass: '35kg'}, {amount: '35'}...] }
  { options: [:mass, :volume, :amount, :packing] }

  # Nested attributes 
  # => { options: {'mass': '35kg', amount: '35', ... } }
  options_attributes: [:mass, :volume, :price, :amount, :packing]
   ) 

经典的方法是使用像这样的嵌套_属性

class Product
  has_one :option # better not write the s to avoid pluralization headaches
  accepts_nested_attributes_for :option

class Option
  belongs_to :product
  field :mass, ...

在这种情况下,强力参数中的声明应该是(不要忘记在没有= f.simple_fields_for :option do |ff|的情况下使用s

但是,如果您没有合适的模型(就像您的情况一样),问题可能来自表单构建器对象,它没有正常运行(因为嵌套模型不存在)。相反,只需使用fields_for(不使用f.simple_

fields_for :options do |ff|