2012-02-08 86 views
7
沒有

很多運氣近來在回答#1(我覺得我的風滾草獎之王),但在這裏不用反正:Rails的更新只空字段

如何更新只能是空場使用activeRecord時?我有這樣的代碼:

master_info.update_attributes({:originalTitle => slave_info.originalTitle,                   
:starring => slave_info.starring, 
:theatrical => slave_info.theatrical } 

,並想是這樣的:

master_info.update_attributes({:originalTitle => slave_info.originalTitle, if !master_info.originalTitle.present?                   
:starring => slave_info.starring, if !master_info.starring.present? 
:theatrical => slave_info.theatrical if !master_info.theatrical.present? } 

我能做到這一條線的時間,但我想避免:

master_info.update_attributes(:originalTitle => slave_info.originalTitle) if !master_info.originalTitle.present? 

我看起來像這樣:

master_info.update_attributes({:originalTitle => slave_info.originalTitle,                   
          :starring => slave_info.starring, 
          :theatrical => slave_info.theatrical }.reject{ |key, value| value.present?}) 

但是,這不起作用,它不會更新任何內容,甚至不會出現空白字段。

實際上,最理想的是不必重複字段名稱,因爲它們在主控和從屬中都被命名爲相同,但我無法在activeRecord上執行.each。但這是第二個問題,主要是更新空字段。

在這裏我們希望這一次沒有得到一個滾草:)

回答

0

您可以覆蓋在模型中使用的update_attributes像這樣

def update_attributes(attributes) 
    attributes.each{|attr| attributes.delete(attr) unless read_attribute(attr).empty?} 
    super(attributes) 
end 

我沒有測試此代碼,然後調整可能需要。

+1

如果你想保持原來的更新方式,你應該定義另一種方法,而不是重載。 – ksol 2012-02-08 16:18:43

+0

對不起,我不明白。如果在接收端爲空,我想更新這些屬性。這段代碼看起來像是從傳入字段中刪除空的屬性。還是我讀錯了? – kakubei 2012-02-08 16:23:16

+0

對不起,我改爲'除非read_attribute(attr).empty?'。 – 2012-02-08 16:56:12

7

稍後在這裏,但認爲我會添加我是如何做的,以防有人發現它有用。

我在第一個答案中使用了函數,並將其修改爲如下。正如@ksol在他的評論中所說的,你可能想保留原來的update_attributes方法,所以我將這一個添加到了我的模型中。我敢肯定,如果您希望將其用於多個型號,它可以包含在全球範圍內。

def update_attributes_only_if_blank(attributes) 
    attributes.each { |k,v| attributes.delete(k) unless read_attribute(k).blank? } 
    update_attributes(attributes) 
end 

這將從散列中刪除任何屬性,除非它已經有一個值。然後它正常更新其餘的屬性。