【问题标题】:rails redirect in controller for a looprails 在控制器中重定向循环
【发布时间】: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


【解决方案1】:

您可以按照 Harsh 的建议将其移动到模型中。你会做这样的事情。然后你就可以摆脱循环了。

class Sale < ActiveRecord::Base

  has_many :items

  # Also make sure you validate children
  validates_associated :items

  validate :items_in_stock

  def items_in_stock
    items.each do |i|
      if i.quantity > i.product.quantity
        i.errors.add(:quantity) = "is not currently available"
      end
    end
  end

end

【讨论】:

    猜你喜欢
    • 2014-09-18
    • 2012-10-03
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多