I am using a lot of my own validation methods to compare the data from one association to the other. I've noticed that I'm constantly checking that my associations aren't nil before trying to call anything on them, but开发者_运维知识库 I am also validating their presence, and so I feel that my nil checks are redundant. Here's an example:
class House < ActiveRecord::Base
has_one :enterance, :class => Door
has_one :exit, :class => Door
validates_presence_of :enterance, :exit
validate :not_a_fire_hazard
def not_a_fire_hazard
if enterance && exit && enterance.location != exit.location
errors.add_to_base('If there is a fire you will most likely die')
return false
end
end
end
I feel like I am repeating myself by checking the existence of enterance and exit within my own validation.
Is there a more "The Rails Way" to do this?
You also might want to consider using the validates_associated
stanza in order to validate whether the associated objects are themselves valid. Also, another cleaner way to go ahead and ensure that both entrance and exit are present (not nil) would be with the following:
validates_presence_of :entrance_or_foo
def entrance_or_foo
entrance and foo
end
Then you can clean up your fire hazard method to look like the following:
def not_a_fire_hazard
if enterance.location != foo.location
errors.add_to_base('If there is a fire you will most likely die')
end
end
You do not need the return false in the definition above.
As noted by Francois in comments, exit is a method defined in the Kernel module. You should rename your class so as to not avoid confusion with the Ruby defined exit method. I've renamed instances of exit to foo in my example code above.
精彩评论