Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR: first_or_initialize block doesn't save

I have the following code, which works fine with no errors but the models never get saved...

myarray.each do |item|

    r = MyModel.unscoped.where(:site_id => @site.id, :url => item['permalink_url']).first_or_initialize do |r|
        r.title              = 'asdasdadaddjfgnfd'
        r.save!
    end
end

Terminal shows the SQL SELECT statements when attempting to find the Models, but the UPDATE/INSERT statements never run.

What am I missing here?

like image 911
Ashley Avatar asked Dec 03 '22 22:12

Ashley


1 Answers

Rails first_or_* methods invoke passed block only for initialize or create part. If the record is found, the methods just return it so passed block will never run. Check the source

So you can use block in first_or_* methods only to initialize new items, not to update existing ones. Most likely, records with such conditions exist and don't get updated.

Try to move update code, something like

myarray.each do |item|

  r = MyModel.unscoped.where(:site_id => @site.id, :url => item['permalink_url']).first_or_initialize
  r.title              = 'asdasdadaddjfgnfd'
  r.save!

end
like image 111
dimuch Avatar answered Dec 05 '22 12:12

dimuch