ruby-on-rails - Ruby on Rails nil 不能被强制转换为 BigDecimal

标签 ruby-on-rails bigdecimal

为什么我会收到 nil can't be coerced into BigDecimal当我尝试执行计算时:这是代码:

型号/drink.rb

class Drink < ActiveRecord::Base
  belongs_to :menu 
  before_save :total_amount 

def total_amount
    self.total_amount = self.price * self.quantity
end 

型号/menu.rb
class Menu < ActiveRecord::Base
    has_many :drinks, :dependent => :destroy
    accepts_nested_attributes_for :drinks, :allow_destroy => true
    #Validations

end

*Drink 是(嵌套)子模型,Menu 是父模型当我尝试创建新饮料时,浏览器显示以下错误消息 nil can't be coerced into BigDecimal app/models/drink.rb:7:in 'total-amount' app/controllers/menus_controller.rb:47:in 'create' app/controllers/menus_controller.rb:46:in 'create'
应用程序/数据库/迁移
class CreateDrinks < ActiveRecord::Migration
  def change
    create_table :drinks do |t|
      t.string :name
      t.decimal :quantity,:precision => 8, :scale => 2
      t.decimal :price, :precision => 8, :scale => 2
      t.decimal :vat, :precision => 8, :scale => 2
      t.references :menu

      t.timestamps
    end
    add_index :drinks, :menu_id
  end
end

Controller /drinks_controller.rb
   class DrinksController < ApplicationController
      # GET /drinks
      # GET /drinks.json
      def index
        @drinks = Drink.all

        respond_to do |format|
          format.html # index.html.erb
          format.json { render :json => @drinks }
        end
      end

      # GET /drinks/1
      # GET /drinks/1.json
      def show
        @drink = Drink.find(params[:id])

        respond_to do |format|
          format.html # show.html.erb
          format.json { render :json => @drink }
        end
      end

      # GET /drinks/new
      # GET /drinks/new.json
      def new
        @drink = Drink.new

        respond_to do |format|
          format.html # new.html.erb
          format.json { render :json => @drink }
        end
      end

      # GET /drinks/1/edit
      def edit
        @drink = Drink.find(params[:id])
      end

      # POST /drinks
      # POST /drinks.json
      def create
        @article = Drink.new(params[:drink])

        respond_to do |format|
          if @drink.save
            format.html { redirect_to @drink, :notice => 'Drink was successfully created.' }
            format.json { render :json => @drink, :status => :created, :location => @article }
          else
            format.html { render :action => "new" }
            format.json { render :json => @drink.errors, :status => :unprocessable_entity }
          end
        end
      end

      # PUT /drinks/1
      # PUT /drinks/1.json
      def update
        @drink = Drink.find(params[:id])

        respond_to do |format|
          if @drink.update_attributes(params[:drink])
            format.html { redirect_to @drink, :notice => 'Drink was successfully updated.' }
            format.json { head :ok }
          else
            format.html { render :action => "edit" }
            format.json { render :json => @drink.errors, :status => :unprocessable_entity }
          end
        end
      end

      # DELETE /drinks/1
      # DELETE /drinks/1.json
      def destroy
        @drink = Drink.find(params[:id])
        @drink.destroy

        respond_to do |format|
          format.html { redirect_to drinks_url }
          format.json { head :ok }
        end
      end 
    end 

请谁能告诉我代码有什么问题?

最佳答案

如果您希望 nil 被评估为 0.0,那么您可以执行以下操作:

def total_amount
    self.total_amount = self.price.to_s.to_d * self.quantity.to_s.to_d
end 

或者明确检查 nil
def total_amount
  if self.price && self.quantity
    self.total_amount = self.price * self.quantity
  else
    self.total_amount = "0.0".to_d
  end
end 

问题实际上是您的记录字段没有像您期望的那样设置。您是否需要使用验证来确保 pricequantity字段设置?
class Drink
  validates :price, :presence => true      # Don't forget add DB validations, too :)
  validates :quantity, :presence => true
end

这样您就可以确保在调用#total_amount 时不会得到 nil 值。

关于ruby-on-rails - Ruby on Rails nil 不能被强制转换为 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7779368/

相关文章:

ruby-on-rails - 如何在 Rails 中使用 postgresql 函数

ruby-on-rails - 带有 rspec 的 rails json.jbuilder api -> ActionView::MissingTemplate

java - 你能让一个 TextField<BigDecimal> 同时接受 , 和 .作为小数分隔符?

javascript - 通过 Google 地方信息显示当前位置

ruby-on-rails - 使用 Capistrano 执行 Rake 任务?

java - Java 中的 toPlainString() 和 toString() 有什么区别?

java - 新的 BigDecimal ("0") NumberFormatException

java - java中的指数

math - ScalaNumber 的实现如何在底层工作?

ruby-on-rails - 如何防止 Rails ActiveRecord before_create 过滤器中的数据库更改在返回 false 时回滚?