Question

I'm trying to create a before_save to set the name of an entry to the date it was created if it was left blank. I got it to work with a method, here is my model:

class Entry < ActiveRecord::Base
  belongs_to :user
  has_many :entry_ingredients
  has_many :ingredients, :through => :entry_ingredients
  before_save :default_name

  accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true

  def default_name
    if self.name.blank?
      self.name = Time.new
    else
      self.name
    end
  end
end

However, what I think is the same code doesn't seem to work in the before_save. Basically, I was trying to do this before_save :default_name, :if => self.name.blank? and then my method would be shorter like so:

def default_name
  self.name = Time.new
end

Why doesn't that if statement on before_save work? I get the error undefined methodbefore_save' for false:FalseClass`

Was it helpful?

Solution

You cant do it this way, because the self.name.blank? gets evaluated when the class gets evaluated for the first time. So you end up with ":if => false" or ":if => true" or an errors occurs.

before_save :default_name, :if => self.name.blank?

In the same file you have an example of how this can be done:

before_save :default_name, :if => lambda { |entry| entry[:name].blank? }

However there are other options. Check the documentation.

OTHER TIPS

You can do like this:

  before_save :default_name

  def default_name
    self.name ||= Time.new
  end

or:

  before_save :default_name, :unless => :name?

  def default_name
    self.name = Time.new
  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top