为什么我的Rails模型不会保存到数据库中?

时间:2013-01-20 22:22:38

标签: ruby-on-rails-3 model

  def self.build_prior_month(payee, as_of = Time.current, opts = {})    
    start_date, end_date, year, month = effective_dates(as_of)

    statement = payee.earnings_statements.build(
      :year => year,
      :month => month,
      :balance => 0,
      :revenue => 0
    )

    statement.generate(start_date, end_date, year, month)
    statement.update_totals

    statement
  end

这是我在我的模型中的一个功能。它正确返回statement,但不保存到数据库。那是为什么?

generate函数如下所示:

  def generate_ledger_items(start_date, end_date, year, month)
    payee.ledger_entries.for_month_and_year(month, year).each do |entry|
      earnings_statement_items.build(
        :items => entry.item_group,
        :units => entry.units,
        :net_revenue => entry.net_revenue,
        :net_revenue_per_unit => [entry.net_revenue, entry.units].all? ? (entry.net_revenue / entry.units).round(2) : nil,
        :fees => entry.service_fees,
        :payments_collected => entry.spendings,
        :fee_terms => entry.terms || entry.description, # When would terms be set?
        :due => entry.credit || -entry.debit
      )
    end
  end

  def update_totals
    self.revenue  = earnings_statement_items.net_revenue
    self.balance = earnings_statement_items.total
  end

2 个答案:

答案 0 :(得分:1)

您的关联上的build方法实际上并未将记录保存到数据库中。 create会。它类似于模型上newcreate之间的差异。

statement = payee.earnings_statements.create(
  :year => year,
  :month => month,
  :balance => 0,
  :revenue => 0
)

将保存您的记录。请参阅documentation

答案 1 :(得分:1)

.build不保存对象

呼叫:

statement.save