Why does Rails check immutable attributes?

It seems validates_uniqueness_of: some_field will work on "save" even if the some_field attribute has not changed (if other fields have changed). This seems wasteful since a database call is required for each validates_uniqueness_of. I know that I can pass Proc to validates_uniqueness_of to check if some_field has changed, and I'm considering going through all the checks and doing it wherever possible. I am wondering:

1) That people interested in performance usually perform their checks?

2) Why is it not validates_uniqueness_ by default to check if an attribute has changed in the first place?

3) Are there any good reasons for performing such checks on attributes that have not changed?

I am using Rails 2.3 (at the moment - we are working on an upgrade). I do not know that this is the same situation in Rails 3.

+3
source share
2 answers

What if someone directly changed the value in the database?

What if some other application (not rails app) also accesses the database?

In all of the above scenarios, you still want your data to be valid, so your rails application behaves as expected. If the data was tampered with (by another application or directly in the database), your rails application throws an error because it does not expect data.

, . , , , , . , , , , , , , , .

+2

Rails 3.0. , , . User, .

class User < ActiveRecord::Base

attr_accessible :email, :password, :ha1, :ha1b, :sip_username, :domain

validates :sip_username, :presence => true, :uniqueness => true,
                         :unless => :update_username?,
                         :exclusion => {:in => %w(9196),
                         :message => "9196 is reserved, please choose another"}
def update_username?
  # check to see if we are updating a sip_username for an existing user
  stored_user = User.find_by_sip_username self.sip_username
  # the id of the user is the same as me and sip_username hasn't been changed. skip validations.
  if (stored_user.present?)
    stored_user.id == self.id && stored_user.sip_username == self.sip_username
  end
end
0

All Articles