rails在控制器中重定向以进行循环

时间:2015-10-12 08:46:43

标签: ruby-on-rails ruby-on-rails-4

我在rails controller中创建了这样的方法:

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置于循环轨道中,则表示错误。怎么做?

1 个答案:

答案 0 :(得分:3)

您可以像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