2012-02-08 88 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 

这将从散列中删除任何属性,除非它已经有一个值。然后它正常更新其余的属性。