Ruby-on-rails 如何将默认值添加到 rails 中的 number_field?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18608004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add default value to a number_field in rails?
提问by Rajdeep Singh
I've created a form
我创建了一个表格
<%= form_for [current_user,@product,@bid] do |f| %>
<p><%= f.number_field :bid_amount %></p>
<p><%= f.number_field :product_id %>
<p><%= f.submit 'Bid!' %></p>
<% end %>
In the :product_id field I want add @product.id by default, how to implement this?
在 :product_id 字段中我想默认添加@product.id,如何实现?
回答by Rajarshi Das
<p><%= f.number_field :product_id, :value => @product.id %></p>
more details on: NumberField
更多详情: NumberField
回答by Miotsu
Just:
只是:
<p><%= f.number_field :product_id, :value => @product.id %></p>
回答by Miotsu
I'm assuming bid belongs to product. Therefore product_id should not be on form at all for the user to see. As an id number it's meaningless and it must be set to the correct product for all bids.
我假设出价属于产品。因此 product_id 根本不应该出现在表单上供用户查看。作为 ID 号,它毫无意义,必须为所有出价设置正确的产品。
The action on the form will automatically mean it gets set correctly in the database.
表单上的操作将自动意味着它在数据库中正确设置。
回答by s01ipsist
user740584 is right, the user should not be able to edit the product_id.
user740584 是对的,用户应该不能编辑 product_id。
If you really do need it on your form you can use a
如果您确实需要在表单上使用它,则可以使用
<%= f.hidden_field :product_id %>
回答by Navazish
Just add @product.id to your field.
只需将@product.id 添加到您的字段即可。
In this example <%= f.number_field :product_id, @product.id %>
在这个例子中 <%= f.number_field :product_id, @product.id %>

