I have a table similar to the following
id | name | address
both name and address are not nullable(this i achieve through attribute setters only and not by default)
When i create a new record without any default values what will be stored in the table?
If the value is null
-> if i store a value (say name="MyName", address="The address"). can i reset it back to null at if needed? I cannot assign null here since my setter wont allow.In 开发者_JAVA百科short - can i unassign a value stored in a record's field using something like
my_object.name.delete
from my controller?
Thanks you
Update-the model setter
def name=(value)
if name.nil? raise "Can't be nil"
end
You can. But first, my assumptions:
- I'm going to assume that you are using
ActiveRecord
and you have a model calledMyModel
in order to treat that table. - 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
精彩评论