Rails仅更新空字段

kak*_*bei 9 activerecord ruby-on-rails-3.1

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

如何在使用activeRecord时仅更新空的字段?我有这个代码:

master_info.update_attributes( {:originalTitle => slave_info.originalTitle,                                                                         
:starring => slave_info.starring,
:theatrical => slave_info.theatrical }
Run Code Online (Sandbox Code Playgroud)

并希望像:

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? }
Run Code Online (Sandbox Code Playgroud)

我可以一次做一行,但我试图避免这样做:

master_info.update_attributes(:originalTitle => slave_info.originalTitle) if !master_info.originalTitle.present?
Run Code Online (Sandbox Code Playgroud)

我读了类似的东西:

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

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

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

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

小智 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
Run Code Online (Sandbox Code Playgroud)

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


Fer*_*ida 0

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

def update_attributes(attributes)
  attributes.each{|attr| attributes.delete(attr) unless read_attribute(attr).empty?}
  super(attributes)
end
Run Code Online (Sandbox Code Playgroud)

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