2012-02-10 17 views
7

mam dwa modele:
User (e-mail: string)
Profile (nazwa: string)
Szyny połączeń aktualizacja delegat

class User < ActiveRecord::Base 
    has_one :profile 
    delegate :name, :name=, :to => :profile 
end 
class Profile < ActiveRecord::Base 
    belongs_to :user 
end 

rails c

u = User.new 
u.build_profile   #=> init Profile 
u.name = 'foo' 
u.email = '[email protected]' 
u.save     #=> both User and Profile are saved 

u.name = 'bar' 
u.save     #=> true, but changes in Profile were not saved! 

u.email = '[email protected]' 
u.save     #=> true, new User email was saved, Profile - still not! 

u.name     #=> 'bar', but in database it's 'foo' 

Dlaczego profil nie jest aktualizowane (zapisywane tylko po raz pierwszy)? Jak to naprawić?

Odpowiedz

1

ta kwestia wygląda znajomo :)

Właśnie próbowałem i to działa:

after_save :save_profile, :if => lambda {|u| u.profile } 

def save_profile 
    self.profile.save 
end 

Sidenote:

Radzę, aby dodać niektóre default scope zawsze załadować profile wzdłuż user jeżeli często używasz obu modeli.