Noz
Noz

Reputation: 6346

Rails 3 How to append a fake record to an ActiveRecord array?

Given the scenario:

Collection of X number of records from "ModelA" is retrieved, processing is then performed on said collection to build records for "ModelB", however X must amount to an even number for processing to take place and processing has to take place no matter what, even if X is an odd number.

Is it possible to perhaps fake a single record in the collection to get an even number so that processing takes place successfully?

To give you an example what what I'm trying to do...

def generate_some_modelb_data
  collection = ModelA.somemethod
  #append fake record if collection is an odd number
  if collection.count%2 > 0
    collection << somefakehash
  end
  #process the collection
  ...
  ModelB.create(:attribute_a => processed_data, :attribute_b => processed_data....)
end

I don't want to store any fake data in ModelA, but it's ok if the fake data that I append to the collection gets stored in ModelB if it allows me to process the legitimate data correctly. I should also add that whatever fake data gets appended shouldn't share any resemblance to existing ModelA records, i.e. ids and so forth, it should be able to be identified as fake data for future processing.

Upvotes: 0

Views: 657

Answers (1)

Matt Winckler
Matt Winckler

Reputation: 2233

Try replacing the collection << somefakehash with collection.append(somefakehash). According to the docs, the << operator instantly fires update SQL without waiting for a save or update on the parent.

Upvotes: 1

Related Questions