代码之家  ›  专栏  ›  技术社区  ›  Satchel

在模型上创建后的rails回调方法是否具有新创建模型的实例?

  •  1
  • Satchel  · 技术社区  · 15 年前

    我有一个联系人模型的后创建方法。

    但是,当我把这个值放进去时,结果是零。如何在回调方法中为新创建的模型(我在创建模型中进行了大量转换)进行回调?

    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的日志时,它没有显示在create方法中使用的任何转换……然而,这应该只在创建(和保存)对象之后运行,对吗?

    创建方法如下:

      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
    
    1 回复  |  直到 15 年前
        1
  •  4
  •   Rishav Rastogi    15 年前

    是的,发生这种情况是因为在为公司对象赋值时没有使用self。

    在Ruby中,通常不需要使用have“self”来检索实例的属性

    例如,在代码中。你可以 puts company 它会很好地工作。

    但是当分配(在左手边)时,你总是必须使用自我。

    所以在代码中更改这个。

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

     
      self.company.phone = phone 
      company.save