保存简单字段时遇到问题

Having problems with simple fields saving

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

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

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

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

对象类型

:options 在这里不是一个简单的字段。要么你希望它是 key/value 对的嵌套散列,

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]
   ) 

经典的方法是这样使用nested_attributes

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, ...

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

但是,如果您没有合适的模型(如您的情况),问题可能来自表单生成器对象,该对象的行为不正常(因为嵌套模型不存在)。而是尝试只使用 fields_for(不使用 f.simple_

fields_for :options do |ff|