2012-02-10 13 views
7

मैं दो मॉडल हैं:
User (ईमेल: स्ट्रिंग)
Profile (नाम: स्ट्रिंग)
रेल प्रतिनिधि अद्यतन कॉल

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' 

क्यों प्रोफ़ाइल अद्यतन नहीं किया जा रहा है (केवल पहली बार सहेजा गया)? इसे कैसे ठीक करें?

उत्तर

10

ArcaneRain, आप के बजाय अपने रिश्ते पर 'स्वतः सहेजना' विकल्प जोड़ना चाहिए कि के लिए एक कॉलबैक जोड़ने की:

has_one :profile, :autosave => true

आप भी 'निर्भर' विकल्प की जाँच करनी चाहिए। अधिक जानकारी यहां: http://guides.rubyonrails.org/association_basics.html#has_one-association-reference

1

यह सवाल परिचित लग रहा है :)

बस इस की कोशिश की और यह काम करता है:

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

def save_profile 
    self.profile.save 
end 

Sidenote:

मैं तुम्हें user अगर अपने साथ कुछ default scope जोड़ने के लिए हमेशा profile लोड करने के लिए सलाह देने के लिए आप अक्सर दोनों मॉडलों का उपयोग करते हैं।

संबंधित मुद्दे