Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails update only empty fields

not having a lot of luck lately with answers in Stackoverflow (I think I'm the king of the tumbleweed award) but here goes anyway:

How can I update only fields that are empty when using activeRecord? I have this code:

master_info.update_attributes( {:originalTitle => slave_info.originalTitle,                                                                         
:starring => slave_info.starring,
:theatrical => slave_info.theatrical }

And would like something like:

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? }

I could do it one line at a time, but am trying to avoid that:

master_info.update_attributes(:originalTitle => slave_info.originalTitle) if !master_info.originalTitle.present?

I read something like:

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

But this doesn't work, it doesn't update anything, not even empty fields.

In fact, what would be ideal is to not have to repeat the field names since they are all named the same in both master and slave, but I can't do a .each on an activeRecord. But that's a secondary problem, the primary one is updating the empty fields.

Here's hoping this one doesn't get a tumbleweed :)

like image 665
kakubei Avatar asked Feb 08 '12 10:02

kakubei


1 Answers

A bit later here but thought I'd add how I did it in case someone finds it useful.

I used the function in the first answer and modified it to the below. As @ksol said in his comment, you probably want to keep the original update_attributes method as is, so I added this one to my model. I'm sure it could be included globally if you wanted it for multiple models.

def update_attributes_only_if_blank(attributes)
    attributes.each { |k,v| attributes.delete(k) unless read_attribute(k).blank? }
    update_attributes(attributes)
end

This removes any attributes from the hash unless the it already has a value. Then it updates the remaining attributes as normal.

like image 82
mchapman17 Avatar answered Sep 27 '22 22:09

mchapman17