Romain Eude
2007-Jan-05 16:33 UTC
polymorphic associations ok in read but not in create...
Hi, I am trying to use polymorphic associations to solve the following problem: I want a general class ''Employee'' which content can come from 2 other classes. The code is: class Employee < ActiveRecord::Base # :assignable is the interface we expose to mask of various employee types. belongs_to :assignable, :polymorphic => true end class User < ActiveRecord::Base # polymorphic association has_many :employees, :as => :assignable #here I am not sure if I should put has_many or has_one ? end class Secretary < ActiveRecord::Base # polymorphic association has_many :employees, :as => :assignable end In Read mode, everything is fine : Employee.find(:first).class # => Employee. Employee.find(:first).assignable.class # => User or Secretary , depending on the data. Now, I am writing my Unit Tests and I want to see if when I create a User, the Employee entry is also created or not. Apparently, User.save does not create a record in Employee, which I mean I have to code this. Am I doing something wrong in my code or is it simply that it is not [yet] implemented in Rails ? thanks in advance. Romain. -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
Romain I''m looking at AWDWR version 2 on page 347 in the section on Polymorphic Associations. It appears that you should be using has_one on your User and Secretary classes, as each User and Secretary is associated with exactly one Employee. (Employee has a one-to-one relationship with a User OR a Secretary, but not both, since a single foreign key (assignable_id) is polymorphically (re)used for both. I think you need to create both sides of the association: e = Employee.new(...) e.assignable = Secretary.new(...) e.save! Patrick --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---