Ruby Rails - 如何通过计算更新数据库?

时间:2015-09-30 20:41:14

标签: ruby-on-rails

我正在开发一个简单的rails应用程序。用户输入两个单独的整数,当他们按“创建”时,“显示”页面显示两个值和第三个值,该值是根据用户输入计算的。我已经把算法用于计算'show'html.erb视图中的第三个值,但我无法弄清楚如何将第三个值添加到数据库中。继承我的'show'视图代码:`     

    命名:     <%= @ startup.name%>     

<p>
<strong>Revenue:</strong>
<%= @startup.revenue %>
</p>

<p>
<strong>Costs:</strong>
<%= @startup.costs %>
</p>
<h2>
<strong>Profit:</strong>
<%= @startup.profit = @startup.revenue - @startup.costs %>

2 个答案:

答案 0 :(得分:0)

您可以为此计算值向数据库添加一列,并在完成计算后更新它。

创建迁移以将列profit添加到startup模型:

rails g migration AddProfitToStartups profit:decimal

注意您可以为profit选择不同的数据类型,具体取决于revenuecosts列的数据类型。还有其他货币助手,请参阅here

这将产生:

class AddProfitToStartups < ActiveRecord::Migration
  def change
    add_column :startups, :profit, :decimal
  end
end

现在运行rake db:migrate来更新数据库。

在此之后,您在视图中使用的代码应该按原样运行。

答案 1 :(得分:-1)

在Startup model call profit中创建一个变量。 在创建动作中有这样的事情:

def create
  @startup = Startup.new(startup_params)
  @startup.profit = @startup.revenue - @startup.costs
  @startup.save
  #redirect
end

显然上面的答案是不好的做法。所以,我希望这是一个更好的更通用的解决方案。

在Startup模型的顶部调用before_save,如下所示:

before_save :calculate_profit

然后在Model中编写一个名为calculate profit的函数。它看起来像这样

def calculate_profit
  self.profit ||= self.revenue - self.costs
end
相关问题