2012-02-10 29 views
7

Tôi có hai mô hình:
User (email: string)
Profile (tên: string)
Rails cập nhật đại biểu gọi

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' 

Tại sao các hồ sơ không được cập nhật (chỉ được lưu lần đầu tiên)? Làm thế nào để sửa lỗi này?

Trả lời

1

Câu hỏi này có vẻ quen thuộc :)

Chỉ cần cố gắng này và nó hoạt động:

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

def save_profile 
    self.profile.save 
end 

Sidenote:

tôi khuyên bạn nên thêm một số default scope luôn nạp profile dọc theo user nếu bạn thường sử dụng cả hai mô hình.

Các vấn đề liên quan