【发布时间】:2015-10-12 08:46:42
【问题描述】:
我在 Rails 控制器中创建了这样的方法:
def create
@sale = Sale.new(sale_params)
@sale.user_id = current_user.id
@sale.total = @sale.total_all
params[:sale][:items_attributes].values.each do |p|
@product = Product.find(p['product_id'])
if @product.quantity.to_i - p['quantity'].to_i <= 0
flash.now[:notice] = "Quantity is higher then stock"
end
end
respond_to do |format|
if @sale.save
format.html { redirect_to @sale, notice: 'Sale was successfully created.' }
format.json { render :show, status: :created, location: @sale }
else
format.html { render :new }
format.json { render json: @sale.errors, status: :unprocessable_entity }
end
end
end
if @product.quantity.to_i - p['quantity'].to_i <= 0
flash.now[:notice] = "Quantity is higher then stock"
end
此条件失败意味着控制器重定向到创建页面本身,否则它需要重定向到索引页面。如果我将render :new 放入循环导轨中,则表示错误。如何做到这一点?
【问题讨论】:
-
这个逻辑必须在Product模型中作为验证器实现,并且必须返回验证错误。
-
发布你得到的确切错误。
-
好的,单一责任。您的控制器不必了解您的业务规则。正如@HarshGupta 所说,您应该关心产品模型中的产品数量。您的控制器只需要设置闪光灯和重定向(或渲染)。使用此控制器“验证”,您可以销售的产品数量超过您的产品数量。
标签: ruby-on-rails ruby-on-rails-4