2015-02-24 36 views
1

我在模型中刪除除了數字以外的所有電話號碼中的以下代碼。before_validation不修改update_attributes後的數據

before_validation :strip_phone_numbers 

def strip_phone_numbers 
    self.home_phone.gsub!(/[^0-9]/, '') if self.home_phone.present? 
    self.work_phone.gsub!(/[^0-9]/, '') if self.work_phone.present? 
    self.mobile_phone.gsub!(/[^0-9]/, '') if self.mobile_phone.present? 
end 

現在這完美的控制器#創建,但更新它不會修改數據。這裏是更新操作:

def update 
    @user = User.find(params[:id]) 
    respond_to do |format| 
    if @user.update_attributes(params[:user]) 
     flash[:success] = 'The user was successfully updated.' 
     format.html { redirect_to(@user) } 
    else 
     format.html { render :action => "edit" } 
    end 
    end 
end 

我的傾向是怪中的update_attributes的before_validation是一些其他的自我運行。但我不確定。

回答

1

當您致電保存時,ActiveRecord將檢查是否有任何屬性已更改。如果沒有改變,它不會更新模型。
使用gsub!您只能抓取字符串並更改其值。這不會告訴ActiveRecord屬性已更改,因此模型將不會更新。
ActiveRecord使用的屬性設定裝置,以保持模型的變化,所以你需要使用它們:

def strip_phone_numbers 
    self.home_phone = self.home_phone.gsub(/[^0-9]/, '') if self.home_phone.present? 
    self.work_phone = self.work_phone.gsub(/[^0-9]/, '') if self.work_phone.present? 
    self.mobile_phone = self.mobile_phone.gsub(/[^0-9]/, '') if self.mobile_phone.present? 
end 
+0

真棒,更多地解釋「不會使ActiveRecord的髒」 – 2015-02-24 18:19:11

+0

更新@Greggawatt。如果需要的話,我可以在晚些時候在家改善它 – Doguita 2015-02-24 18:42:23