Shamoon
Shamoon

Reputation: 43609

Why won't my Rails model save into the Database?

  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

That's a function that I have in a model of mine. It returns statement properly, but doesn't save to the database. Why is that?

The generate function looks like:

  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

Upvotes: 0

Views: 227

Answers (2)

Marcel Hebing
Marcel Hebing

Reputation: 3182

.build doesn't save the object

call:

statement.save

Upvotes: 1

Logan Serman
Logan Serman

Reputation: 29880

The build method on your association does not actually save the record into the database. create will. It is similar to the difference between new and create on your models.

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

Will save your record. See the documentation.

Upvotes: 1

Related Questions