2011-03-10 56 views
5

所以我有一個上有可編輯的字段...簡單的更新的對接負荷編輯頁面... @patient.update_attributes(params[:patient]) ...一切都很好,除了....領域的update_attributes調整

我得趕緊一個字段這些20,我需要調整有點它已經準備好爲DB之前,它似乎我要不要做

  1. 兩趟
    @patient.update_attributes(params[:patient])
    @patient.update_attribute(:field=>'blah')

  2. 或單獨設置他們都
    patient.update_attributes(:field1=>'asdf', :field2=>'sdfg',:field3=>'dfgh', etc...)

我缺少一個辦法做到這一點是一舉?

回答

2

您可以爲該字段創建虛擬屬性。說這個字段是:名字。你在你的患者模型一樣創建一個函數:

def name 
    self[:name] = self[:name] * 2 
end 

,當然還有,你做你的事情,函數內部:) Instaed的自我[:名字],您也可以使用read_attribute(:名稱)。

4

你需要調整的屬性是什麼?有兩種方法可以做到這一點:

無論是按摩PARAMS您將它們發送到update_attribute方法之前:

我只是給一個例子在這裏,如果你想強調的一個值:

params[:patient][:my_tweak_attribute].gsub!(" ", "_") 
@patient.update_attributes(params[:patient]) 

再有就是在模型中的before_save或before_update回調做你扭捏的首選方式:

class Patient < ActiveRecord::Base 
    before_update :fix_my_tweak_attribute, :if => :my_tweak_attribute_changed? 

    protected 
    def fix_my_tweak_attribute 
     self.my_tweak_attribute.gsub!(" ", "_") 
    end 
end 

這樣可以使你的控制器清理它可能不需要的代碼。

如果你只需要添加一個沒有得到通過的形式發送一個新的PARAM你可以在控制器中這樣做:

params[:patient][:updated_by_id] = current_user.id 
@patient.update_attributes(params[:patient]) 

假設current_user爲你的地方(指再次,只是一個例子)