2010-11-02 51 views
1

我對我的聯繫人模型有一個after_create方法。在模型上做了after_created Rails回調方法是否有新創建模型的實例?

但是,當我把它的價值,它出來無。如何在回調方法中引用新創建的模型(我在創建模型中進行了相當數量的轉換)的回調?

after_save :update_company 

def update_company 

    puts self.inspect 
    puts self.company 

    if company.phone.empty? 

     company.phone = self.phone 
     company.save 

    end  

end 

當我看日誌self.inspect,它不顯示任何在創建方法中使用的變換......然而,這應該運行它創造了(並保存)後,才,對象,對吧?

下面是創建方法:

def create 

    @contact = Contact.create(params[:contact]) 

    unless @contact.vcard.path.blank? 

      paperclip_vcard = File.new(@contact.vcard.path) 

     @vcard = Vpim::Vcard.decode(paperclip_vcard).first 
     @contact.title = @vcard.title 
     @contact.email = @vcard.email 
     @contact.first_name = @vcard.name.given 
     @contact.last_name = @vcard.name.family 
     @contact.phone = @vcard.telephone 
     @contact.address.street1 = @vcard.address.street 
     @contact.address.city = @vcard.address.locality 
     @contact.address.state = @vcard.address.region 
     @contact.address.zip = @vcard.address.postalcode 
     @contact.company_name = @vcard.org.fetch(0) 

    end 

    @contact.user_id = current_user.id # makes sure every new user is assigned an ID  
    if @contact.save 
     flash[:notice] = "Successfully created contact." 
     redirect_to @contact 
    else 
     render :action => 'new' 
    end 
    end 
+0

'如果company.phone.blank?'嘗試 – s84 2010-11-02 03:37:16

+0

我把一大堆東西在創建方法....沒有後創建意味着它會做之後它通過創建方法......因爲它似乎沒有這樣做...... – Angela 2010-11-02 04:27:26

回答

4

是的,這是因爲你分配價值公司對象時沒有使用自己。

在Ruby中,一般不要求使用具有「自我」在你的代碼來檢索例如一個實例

的屬性。你可以puts company,它會正常工作。

但是當分配時(在左邊),你總是必須使用自我。

所以在你的代碼中改變它。

 
    self.company.phone = self.phone 
    company.save 

 
    self.company.phone = phone 
    company.save 
+0

實際上,我發現如果控制器有一個創建,它使用它作爲保存,所以它發生得太快。 .. – Angela 2010-11-24 04:52:48

相關問題