46

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?

5 Answers 5

81
 <p><%= f.number_field :product_id, :value => @product.id %></p>

more details on: NumberField

4
  • No default value will show once nothing is input by user on that box otherwise it will take the input value given by user....... same as text box Commented Sep 4, 2013 at 8:10
  • 8
    if user given some other value and submit the form then it will take that value not the default value....**default means if nothing was inputed it will take that value as an default** Commented Sep 4, 2013 at 8:25
  • You should probably use @bid.product_id || @product.id so that whatever value is set in the form is used and then only if that is nil does it default to @product.id. Commented May 30, 2019 at 15:10
  • We usually need default value in case a value is very commonly used and we want to save the user's time in that value's case. For example, a site used chiefly by males would have gender set at male but female option will be present just-in-case. In essence, this answer is perfectly OK and user can change the value when they need to.
    – ARK
    Commented Dec 3, 2019 at 18:45
6

Just:

<p><%= f.number_field :product_id, :value => @product.id %></p> 
0
3

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.

1

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 %>
-2

Just add @product.id to your field.

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.