I'm assuming you don't want to create a Person if your User
validations fail and vice versa. One way to do it is as follows. This
will validate your Person during the validation phase for User, and if
all is good save your Person then save User. Note that this doesn't
preclude any database constraint/error from screwing up your User
save, resulting in orphaned Persons. To be really safe you should wrap
both Person and User save operations in a transaction (http://
api.rubyonrails.org/classes/ActiveRecord/Transactions/
ClassMethods.html).

class User < ActiveRecord::Base
 bleongs_to :person, :validate => true

 before_validation :create_person
 before_create :save_person

 def create_person
    if person.nil? && person_id.nil?
      self.person = Person.new(:name => email, :tenant => tenant)
    end
  end

 def save_person
  self.person.save!
 end
end

On Aug 27, 12:42 pm, J. Pablo Fernández <pup...@pupeno.com> wrote:
> Hello,
>
> I have two models, User and Person. Basically users are users of the system
> while people is a kind of address book. But every user is also a person so I
> created this relationship:
>
> class User < ActiveRecord::Base
>   belongs_to :person
> end
>
> class Person < ActiveRecord::Base
>   has_one :user
> end
>
> Now, on creating a user I want to automatically create a person. Is this the
> way to do it:
>
>   before_validation :create_person
>
>   def create_person
>     if person.nil? && person_id.nil?
>       self.person = Person.create!(:name => email, :tenant => tenant)
>     end
>   end
>
> Thanks.

-- 
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@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to