calyxofheld
calyxofheld

Reputation: 2128

set default value of attribute in rails

I need to set the default value for an attribute initial_collection_amount to a calculation which is based off another attribute amount. initial_collection_amount is nil until the record has been persisted, so after_create triggers a validation error:

after_create :set_initial_collection_amount
def set_initial_collection_amount
 self.initial_collection_amount ||= self.amount * 0.15
end

That results in something like initial_collection_amount cannot be blank.

Setting initial_collection_amount to 0 with an after_initialize and then running the above after_create seems sloppy, and in fact doesn't even work the way I'd think it would. I added a puts to each for the terminal output, like so:

after_initialize :set_initial_collection_amount_to_0
after_create :set_initial_collection_amount_x_15
def set_initial_collection_amount_to_0
  puts "a"
  self.initial_collection_amount ||= 0
end

def set_initial_collection_amount_x_15
  puts "b"
  total = self.amount * 0.15
  self.initial_collection_amount ||= total
end

Terminal output from that shows the a in the puts statement 15 times.

How would I do this? I just want that one attribute to be saved. If I add allow_nil: true to the validations it just saves as blank.

Upvotes: 0

Views: 341

Answers (1)

matthewd
matthewd

Reputation: 4420

If you need the value set immediately before the record is created, a before_create event seems more appropriate for your use case.

Upvotes: 1

Related Questions