简体   繁体   English

无法弄清楚为什么表单无法保存到Rails上的数据库ruby中

[英]Can't figure out why form won't save to database ruby on rails

I am trying to save a "product" aka pair of glasses to a database with the following data fields-- Name, Lens, Frame, Temple, Accent, Quantity, Photo. 我正在尝试将一副“产品”眼镜(又名“眼镜”)保存到具有以下数据字段的数据库-名称,镜头,镜框,镜腿,口音,数量,照片。

app/controllers/product_controller.rb 应用程序/控制器/ product_controller.rb

def create
   @product = Product.create(product_params)

end

# Each pair of glasses has a name, lens, frame, accent, quantity, and picture
def product_params
   params.require(:product).permit(:name, :lens_id, :frame_id, :temple_id, :accent_id, :quantity, :photo)
end

app/views/products/_form.html.erb 应用程序/视图/产品/ _form.html.erb

<div class="field">
    ....
    <%= f.label :quantity %>
    <%= number_field_tag :quantity, nil, class: 'form-control', min: 1
</div>  

I can save the record and everything saves to the database except quantity which saves as 'nil'. 我可以保存记录,所有内容都保存到数据库中,数量另存为“ nil”。 I can go into the rails console, select that record, and manually add a quantity via the console though... what am I missing? 我可以进入Rails控制台,选择该记录,然后通过控制台手动添加数量,但是……我还缺少什么?

Thanks in advance! 提前致谢!

The error is a result of the helper tag you are using for :quantity . 该错误是由于您用于:quantity的辅助标签的结果。 You should be using the form builder helper number_field and not the generic number_field_tag . 您应该使用表单构建器帮助程序number_field而不是常规的number_field_tag

It should look like this: 它看起来应该像这样:

<%= f.number_field :quantity, nil, class: 'form-control', min: 1 %>

If this isn't working for you, perhaps due to your version of Rails, you can override the type attribute on text_field and try: 如果这对您不起作用,可能是由于您的Rails版本引起的,您可以覆盖text_field上的type属性并尝试:

<%= f.text_field :quantity, nil, class: 'form-control', type: :number, min: 1 %>

If you want to know why, you will need to understand how Rails is building the POST form data. 如果您想知道为什么,则需要了解Rails如何构建POST表单数据。 Using the form builder form_for you will see that all of the form fields follow the convention object_class[attribute] . 使用表单构建器form_for您将看到所有表单字段都遵循约定object_class[attribute] In your example it'd make product[name] , product[lens_id] , etc... 在您的示例中,它将为product[name]product[lens_id]等。

By using number_field_tag it created an input with the name quantity but you need it to be product[quantity] so that when you call Product.create(product_params) it includes that provided value. 通过使用number_field_tag它创建了一个带有quantity名称的输入,但您需要将其作为product[quantity]以便在调用Product.create(product_params)该输入将包含提供的值。

Your code is producing this for the params: 您的代码正在为参数生成此代码:

 { 
   product:  
   {
     name: '...',
     lens_id: 1
   },
   quantity: 1
 }

vs what is expected: 与预期结果:

{
  product:
  {
    name: '...',
    lens_id: 1,
    quantity: 1
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM