Reputation: 409
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
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
<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'. I can go into the rails console, select that record, and manually add a quantity via the console though... what am I missing?
Thanks in advance!
Upvotes: 1
Views: 1167
Reputation: 1857
The error is a result of the helper tag you are using for :quantity
. You should be using the form builder helper number_field
and not the generic 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:
<%= 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. Using the form builder form_for
you will see that all of the form fields follow the convention object_class[attribute]
. In your example it'd make product[name]
, product[lens_id]
, etc...
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.
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
}
}
Upvotes: 2