2011-01-05 51 views
1

我有他在控制器的更新操作中的代碼。代碼工作時創建,但似乎並沒有踢下更新:如何從Rails中的編輯/更新中更改inpus?

def update 
@contact = Contact.find(params[:id]) 

# bug, why isn't this working? 
unless @contact.fax.empty? 
    @contact.fax = "1" + Phony.normalize(@contact.fax) 
end 

unless @contact.phone.empty? 
    @contact.phone = "1" + Phony.normalize(@contact.phone) 
end 

if @contact.update_attributes(params[:contact]) 
    flash[:notice] = "Successfully updated contact." 
    redirect_to @contact 
else 
    render :action => 'edit' 
end 

回答

6

這些應該是你的模型。 FAT模式,緊身控制器:

# contact.rb 
... 
# may need require 'phony' and include Phony 
before_save :prep 

def prep 
    self.fax = 1+Phony.normalize(self.fax) unless self.fax.empty? || (self.fax.length == 11 && self.fax[0] == 1) 
    self.phone = 1+Phony.normalize(self.phone) unless self.phone.empty? || (self.phone.length == 11 && self.phone[0] == 1) 
end 
... 

編輯:

正如我在我的評論中提到,它在存儲和效率和索引方面更好地爲BIGINT的無符號存儲在數據庫中,並添加對方法中的數字可愛。這樣,你的網站總是被標準化(沒有兩個電話號碼看起來不一樣,因爲它們是'即時'格式化的)。

# sample methods 
def phony 
    str = self.phone.to_s 
    "#{str[0..2]}-#{str[3..5]}-#{str[6..10]}" 
end 

# use a similar method for faxing, but I'll write 
# this one differently just to show flexibility 
def faxy 
    str = self.fax.to_s 
    "+1 (#{str[0..2]}) #{str[3..5]}-#{str[6..10]}" 
end 
+0

@Angela - 爲您做了這項工作嗎? – sethvargo 2011-01-10 02:22:09

+0

我正在嘗試它...我嘗試了nother方法...我希望這個作品,我喜歡它... – Angela 2011-01-11 01:30:44

+0

@ seth.vargo不要太離題遠... ... heheh,你會知道如何使用shoulda來爲此寫一個測試?我不確定.... – Angela 2011-01-11 01:32:18

1

你永遠不會呼籲@contactsaveunless塊,所以你要@contact.update_attributes(params[:contact])通話撤銷你在那些塊所做的任何更改(因爲在params哈希那些鍵對應的空值)。

def update 
    @contact = Contact.find(params[:id]) 

    if @contact.update_attributes(params[:contact]) 
    @contact.update_attributes(:fax => "1" + Phony.normalize(@contact.fax)) unless @contact.fax.empty? 
    @contact.update_attributes(:phone => "1" + Phony.normalize(@contact.phone)) unless @contact.phone.empty? 

    flash[:notice] = "Successfully updated contact." 
    redirect_to @contact 
    else 
    render :action => 'edit' 
    end 
end 

您可以使用update_attribute但繞過驗證。

你也可以使用一個before_save回調在Contact類,但你必須檢查phonefax已經「正常化」。

+0

這應該修復它,所以我不會添加答案。請注意,您需要在UPDATE方法中處理POST參數,然後它們將存在於模型中。不要緊,如果你在更新屬性之前或之後保存它,但直到你更新屬性,從窗體輸入的內容不能通過'@ contact.fax'等東西獲得。 – Andrew 2011-01-05 02:01:11

+0

好吧,我想我明白了......如果我將標準化放入模型中,即使更新也會這樣做嗎? – Angela 2011-01-05 15:55:13