activerecord – Rails仅更新空字段

最近在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,:theatrical => slave_info.theatrical }.reject{ |key,value| value.present?} )

但这不起作用,它不会更新任何内容,甚至不会更新空字段.

事实上,理想的是不必重复字段名称,因为它们在主服务器和从服务器中都被命名为相同,但我不能在activeRecord上执行.each.但这是次要问题,主要问题是更新空字段.

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

解决方法

稍后在这里,但我想我会添加我是如何做的,以防有人发现它有用.

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

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...