Can't figure out why form won't save to database ruby on rails -
i trying save "product" aka pair of glasses database 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 name, lens, frame, accent, quantity, , 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 record , saves database except quantity saves 'nil'. can go rails console, select record, , manually add quantity via console though... missing?
thanks in advance!
the error result of helper tag using :quantity. should using form builder helper number_field , not generic number_field_tag.
it should this:
<%= f.number_field :quantity, nil, class: 'form-control', min: 1 %> if isn't working you, perhaps due version of rails, can override type attribute on text_field , try:
<%= f.text_field :quantity, nil, class: 'form-control', type: :number, min: 1 %> if want know why, need understand how rails building post form data. using form builder form_for see of form fields follow convention object_class[attribute]. in example it'd make product[name], product[lens_id], etc...
by using number_field_tag created input name quantity need product[quantity] when call product.create(product_params) includes provided value.
your code producing params:
{ product: { name: '...', lens_id: 1 }, quantity: 1 } vs expected:
{ product: { name: '...', lens_id: 1, quantity: 1 } }
Comments
Post a Comment