错误消息
我正在尝试通过'number_field_tag'插入一个数字值但是仍然会收到相同的错误消息。有谁知道造成这种情况的原因是什么?
new.html.erb
<% provide(:title, 'Products') %>
<h1>Products</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= render 'shared/error_messages_p' %>
<%= form_for([:admin, @product], :html => {multipart:true}) do |f| %>
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<%= f.label :description %>
<%= f.text_area :description, :rows => 6, class: 'form-control' %>
<%= f.file_field :image %>
<%= number_field_tag :stock_quantity, 1, min: 1, class: "form-control" %>
<%= f.label :price %>
<%= f.text_field :price, class: 'form-control' %>
<%= f.submit "Create product", class: "btn btn-primary" %>
<% end %>
</div>
</div>
products_controller.rb
class Admin::ProductsController < Admin::BaseController
before_action :set_product, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_product
def index
@products = Product.all
end
def show
@product = Product.find(params[:id])
end
def new
@product = Product.new
end
def edit
end
def create
@product = Product.new(product_params)
if @product.save
redirect_to [:admin, @product], notice: 'Product was successfully created.'
else
render :new
end
end
def update
if @product.update(product_params)
redirect_to @product, notice: 'Product was successfully updated.'
else
render :edit
end
end
def destroy
@product.destroy
redirect_to products_url, notice: 'Product was successfully destroyed.'
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :description, :image, :price, :stock_quantity)
end
def invalid_product
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to products_url, notice: 'Invalid product'
end
end
产品型号
class Product < ActiveRecord::Base
attr_accessor :image
validates :title, :description, :image, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :stock_quantity, numericality: { only_integer: true}
validates :image, allow_blank: true, format: {with: %r{\.(gif|jpg|png)\Z}i, message: 'must be a URL for GIF, JPG or PNG image.'}
mount_uploader :image, ImageUploader
答案 0 :(得分:0)
通过将数量提交代码替换为:
来解决问题 <%= f.label :stock_quantity %>
<%= f.number_field :stock_quantity, min: 1, class: 'form-control' %>
任何人都可以告诉我为什么&#39; number_field_tag&#39;不工作?
答案 1 :(得分:0)
这解决了,
<%= number_field_tag 'product[stockquantity]', min: 1, class:"form-control" %>
感谢以前的评论者突出显示的html措辞。