Ruby on rails 如何用其他表中的数据填充rails表?

Ruby on rails 如何用其他表中的数据填充rails表?,ruby-on-rails,ruby-on-rails-3,database-design,Ruby On Rails,Ruby On Rails 3,Database Design,我有点像个noob程序员,所以如果问题不够清楚,我道歉 我正在尝试创建一个基本的rails应用程序,其中有3个不同的表:usages(month,usage)、price(month,price)和spend(month,spend)。 我正试着得到它,这样花费=用法。用法*价格。价格。我已将以下代码放入我的支出模型中: class Spend < ActiveRecord::Base c = Usage.all.count i = 1 while i <

我有点像个noob程序员,所以如果问题不够清楚,我道歉

我正在尝试创建一个基本的rails应用程序,其中有3个不同的表:usages(month,usage)、price(month,price)和spend(month,spend)。 我正试着得到它,这样花费=用法。用法*价格。价格。我已将以下代码放入我的支出模型中:

class Spend < ActiveRecord::Base
  c = Usage.all.count
      i = 1
      while i <= c
          u = Usage.find(i)
          p = Price.find(i)
          Spend.create(month:u.month, spend:u.usage*p.price)
          i += 1
      end
end
class-Spend当我查看Active Record association guide时:

在这种情况下,我会倾向于创建一个单独的
花费
模型,因为它所做的只是计算数据库中已经存在的数据。除非您有严格的缓存要求(我对您的情况表示怀疑),否则您可以使用简单的实例方法来检索所需的数据

首先找出你的使用和价格模型之间的关系。由于您似乎是通过id将它们关联起来,所以这似乎是一对一的关系(如果我在这方面有错,请纠正我)。但是,通过假设它们具有相同的主键进行关联是一种危险的方法,而不是使用外键将一个模型点与另一个模型点进行关联。我们将选择
Price
模型来保存
用法的主键,但反过来也可以。您需要使用如下迁移方式添加列:

def change
  add_column :prices, :usage_id, :integer
end
class Usage < ActiveRecord::Base
  has_one :price

  def spend
    usage * price.price
  end
end

class Price < ActiveRecord::Base
  belongs_to :usage
end
usage = Usage.find(some_id)
puts usage.spend
Usage.include(:price).each do |usage|
  puts usage.spend
end
然后,您的模型应如下所示:

def change
  add_column :prices, :usage_id, :integer
end
class Usage < ActiveRecord::Base
  has_one :price

  def spend
    usage * price.price
  end
end

class Price < ActiveRecord::Base
  belongs_to :usage
end
usage = Usage.find(some_id)
puts usage.spend
Usage.include(:price).each do |usage|
  puts usage.spend
end
或者,您可以获得如下多种“支出”:

def change
  add_column :prices, :usage_id, :integer
end
class Usage < ActiveRecord::Base
  has_one :price

  def spend
    usage * price.price
  end
end

class Price < ActiveRecord::Base
  belongs_to :usage
end
usage = Usage.find(some_id)
puts usage.spend
Usage.include(:price).each do |usage|
  puts usage.spend
end

我省略了对月份的任何引用,因为我不确定您是如何使用它的,或者是否需要它来计算
支出

您是否熟悉ActiveRecord关联(属于,有很多)?啊,太好了,谢谢!我尝试了很多方法,但没有很好地实现。是的,这个月的部分是为了下一步要做的另一个计算(毫无疑问,当我以某种迂回的方式得到它时,我会回到这里)。干杯