views:

33

answers:

1

We have an ActiveRecord model whose columns have some default values. It also has a validation condition such that, if the 'profile' property is set to a different value, then the default values are invalid.

What I'd like is to be able to determine whether the attributes have been set since they were set to the default so that I can reset them to new, valid values before validation.

Is this possible?

UPDATE: It's not clear what I mean, so I should give code examples.

The table is defined like this:

t.column :profile, :string
t.column :contact_by, :string, :default => "phone", :null => false

The validation is like this:

validate :validate_contact_by_for_profile1
def validate_contact_by
  if (profile == "profile1") && (contact_by != "email")
    errors.add(:contact_by, " must be 'email' for users in profile1")
  end
end

So any time we do this:

u = User.new
u.profile => profile1

We end up with u being invalid. What I want to end up with is that the user's contact_by defaults to "phone", but if their profile is set to profile1, then it changes to "email", unless it has been set to something in the meantime. (Ideally this includes setting it to "phone")

A: 

EDITED ANSWER: ok, don't know if I understood, but I'll try :P

you can writing a method to ovveride the profile= setter:

def profile=(value)
  self.contact_by = 'email' if value == 'profile1'
  super
end

this way works as you expect:

> n = YourModel.new
 => #<YourModel id: nil, profile: nil, contact_by: "phone", ...>
> n.profile = 'profile2'
 => "profile2"
> n.contact_by
 => "phone"
> n.profile = 'profile1'
 => "profile1"
> n.contact_by
 => "email"

as you can see, this way you get want you want. then you can do whatever validation you need .

hope this time helped ;-)

OLD ANSWER: generally, you set default values during db migration. so when you try to save some data, the ActiveRecord model has blank data, then when saved on db, it gets default values.

according to this, you can play with validations in the model using something like this:

validates_presence_of :some_field, :if => Proc.new {|m| p.profile != <default value>}

alternatively, you can write a custom validation code, as private method, that will be called from validate:

validate :your_custom_validation_method, :if => Proc.new {|m| p.profile != <default value>}

btw I suggest you to look at ActiveRecord validations docs: http://guides.rails.info/active_record_validations_callbacks.html

apeacox
@apeacox: thanks - looks like I need to explain my question better. I'll have a go.
Simon
ok, check my new reply ;)
apeacox