ruby on rails - How do I make sure an association's attribute is correct to validate the association? -


i've got simple user: **edited bit clarity, , on sam's suggestion

class user < activerecord::base   # <snip other attribs>   has_many :handles   has_one :active_handle, :class_name => "handle"    validates_each :active_handle, :allow_nil => true  |record, attr, value|     record.errors.add attr, "is not owned correct user" unless record.handles.include?(value)   end end 

and handle model:

class handle < activerecord::base   belongs_to :user   attr_accessible :user_id   validates :user_id,         :presence => true,         :numericality => true    attr_accessible :name   validates :name,         #etc... end 

now i'd check, when setting user.active_handle association, handle owned correct handle.user_id. i've tried in custom validation, , in validate method on user model. both ways, exact opposite of want, sets user_id of handle user doing checking.

i'm @ end of rope, don't understand something, , google isn't getting me anywhere haven't been.

eta: have tried manipulate has_one association conditions, seems fail too...

has_one :active_handle,         :class_name => "handle",         :conditions => ['user_id =?', '#{self.id}'] 

i'd take different approach problem; double link messy, , hard maintain, you've discovered. instead, i'd put active flag in handle model, , order :active_handle association on flag:

class user < activerecord::base     has_many :handles     has_one  :active_handle, :class_name => 'handle', :order => 'handles.active desc' end 

now there's 1 link, , it's same link that's in place establish plain has_many :handles association (namely, user_id attribute in handle model). finding active handle in matter of finding user's first handle active flag set. , i'd use :order rather :conditions, that'll give nice fallback: if no handle user has active flag set, rails'll pick 1 use default.

and then, in handle model, can have simple activate function:

class handle < activerecord::base     # ...stuff...      def activate!         # pseudocode - sorry!         sql('update handles set active = 0 user_id = ?', self.user_id)         self.active = true         self.save!     end end 

or, if wanted able call user.handles.activate(hdl), put similar association extension. or user.active_handle = hdl. or...

hope helps!


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -