How to add default value to a number_field in rail

2019-03-09 16:28发布

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? Please. Thanks in advance. :)

5条回答
爷、活的狠高调
2楼-- · 2019-03-09 16:43

Just:

<p><%= f.number_field :product_id, :value => @product.id %></p> 
查看更多
Animai°情兽
3楼-- · 2019-03-09 16:45

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.

The action on the form will automatically mean it gets set correctly in the database.

查看更多
仙女界的扛把子
4楼-- · 2019-03-09 16:49
 <p><%= f.number_field :product_id, :value => @product.id %></p>

more details on: NumberField

查看更多
何必那么认真
5楼-- · 2019-03-09 16:52

user740584 is right, the user should not be able to edit the product_id.

If you really do need it on your form you can use a

<%= f.hidden_field :product_id %>
查看更多
Lonely孤独者°
6楼-- · 2019-03-09 17:00

Just add @product.id to your field.

In this example <%= f.number_field :product_id, @product.id %>

查看更多
登录 后发表回答