在rails中更新大十进制列的更简单方法?

时间:2015-09-09 20:23:09

标签: ruby-on-rails activerecord

我正在构建一个简单的预算应用程序,并且有一行感觉错综复杂且过于复杂的代码。对于上下文:

class User < ActiveRecord::Base
  has_one :month_budget
  has_many :expenditures, as: :spendable
end

class MonthBudget < ActiveRecord::Base
  belongs_to :user
  has_many :expenditures, as: spendable
end

class Expenditure < ActiveRecord::Base
  belongs_to :spendable, polymorphic: true
end

在我的支出类中,我定义了一个类方法add_expenditure:

class Expenditure < ActiveRecord::Base
  def self.add_expenditure(user, params) #params passed will be in [:expenditure][*keys], in which possible keys are [:amount] or [:location]
    if user.month_budget
      user.month_budget.expenditures.create(params)
      new_amount = user.month_budget.current_amount += params[:amount].to_d
      user.month_budget.update(current_amount: new_amount)
    end
  end
end

是否有更有效的方法将值添加到初始month_budget.current_amount列,然后将此新数字记录到数据库中?

提前干杯!

1 个答案:

答案 0 :(得分:0)

也许您可以尝试<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <div class="bs-example"> <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">1. What is HTML?</a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse in"> <div class="panel-body"> <p>HTML stands for HyperText Markup Language. HTML is the main markup language for describing the structure of Web pages. <a id="button1">Learn more.</a></p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">2. What is Bootstrap?</a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse"> <div class="panel-body"> <p>Bootstrap is a powerful front-end framework for faster and easier web development. It is a collection of CSS and HTML conventions. <a href="http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/" target="_blank">Learn more.</a></p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">3. What is CSS?</a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse"> <div class="panel-body"> <p>CSS stands for Cascading Style Sheet. CSS allows you to specify various style properties for a given HTML element such as colors, backgrounds, fonts etc. <a href="http://www.tutorialrepublic.com/css-tutorial/" target="_blank">Learn more.</a></p> </div> </div> </div> </div> </div> </body>方法(http://apidock.com/rails/v4.2.1/ActiveRecord/Persistence/increment%21)。

但是,我不确定它是否适用于小数字。

increment!