Rails仅更新空字段

时间:2012-02-08 10:34:57

标签: activerecord ruby-on-rails-3.1

最近在Stackoverflow中没有很多运气(我认为我是风滚草奖的国王)但是无论如何都要去了:

如何在使用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。但这是次要问题,主要问题是更新空字段。

这里希望这个没有风滚草:)

2 个答案:

答案 0 :(得分:9)

稍后这里,但我想我会添加我是如何做的,万一有人发现它有用。

我在第一个答案中使用了该功能并将其修改为以下内容。正如@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

除非已经有一个值,否则这将删除散列中的所有属性。然后它正常更新剩余的属性。

答案 1 :(得分:0)

您可以使用类似的内容覆盖模型中的update_attributes

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

我没有测试此代码,因此可能需要进行调整。