微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/ruby/270133.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐