js5yrq
Last Updated: February 25, 2016
·
747
· mrako
4fe949ea9ee7c0bc5eb4bf3e17b09d75

Add inverse_of to upgrade to Rails 3.2.11 (to fix the security hole)

As you hopefully already know, there is a severe security issue in Rails versions before 3.2.11, 3.1.10, 3.0.19 and 2.3.15.

If you are running Rails 3.2.8 or below, and have not yet added inverse_of to your ActiverRecord::Associations, you might be in for a big bunch of changes before the update.

Autoupdating Your Models

I created a small script to update your models. It's not that pretty, but does what is expected: updates has_many and belongs_to associations with the correct inverse_of clause.

add_inverse_of.rb

#!/usr/bin/env ruby
require 'active_support/inflector'

Dir.glob("#{Dir.pwd}/*.rb") do |file|
  basename = File.basename(file, ".rb")

  lines = IO.readlines(file).map do |line|
    if line.match(/(belongs_to|has_many (((?!through)(?!inverse_of).)*)$)/)
      line.sub(/has_many ([^\n]*)/){|m| "has_many #{$1}, inverse_of: :#{basename}"}.sub(/belongs_to ([^\n]*)/){|m| "belongs_to #{$1}, inverse_of: :#{basename.pluralize}"}
    else
      line
    end
  end

  File.open(file, 'w') do |file|
    file.puts lines
  end
end

It's very simple to use. If you have Rails installed in your RVM environment, just run the following in the root of your Rails App:

$ cd app/models
$ ruby <location of the script>/add_inverse_of.rb

If you have a clean Ruby environment, you might need to run $ bundle exec ruby add_inverse_of.rb

Fixing other Issues

You might not have created all of your model associations as bi-directional in the first place, as the earlier Rails versions didn't force it. This is a very good time to fix the consistency of your app and check your factories and specs (or any other combination of fixtures and tests) verify your application still works as expected.

Say Thanks
Respond