views:

55

answers:

1
+1  A: 

You can. But first, my assumptions:

  1. I'm going to assume that you are using ActiveRecord and you have a model called MyModel in order to treat that table.
  2. I'm going to assume that you used the proper way to make fields non-nullable, which is by using validations. If this is not the case, I strongly suggest that you reconsider using them.

Then you can do:

class MyModel < ActiveRecord::Base
  validates_pressence_of :name, :if => :check_name

  attr_writer :check_name
  def check_name # make it defalt to true
    @check_name = @check_name.nil? ? true : @check_name
  end
end

You can use it like this:

my_object.name = "Josh"
my_object.save # ok
my_object.name = ""
my_object.save # not ok
my_object.check_name = false
my_object.save # ok
egarcia
When assigning my_object.name, can you give it a nil? At the DB level, there is a difference between a NULL column and a column with an empty string, I think.
Terry Lorber
At the db level there is, but validates_presence_of is intelligent enough not to be fooled by an empty string. It will bark if you try to put any "non-empty" value on the name - a nil, an empty string, or an empty array if I remember correctly.
egarcia