Tag: ActiveModel

Upgrading to Rails 4.0 from Rails 3.2 – Test case – Part II (assets, models)

Here's the second part of tutorial on how to migrate from Rails 3.2 to Rails 4.

Assets - why aren't they working in a proper way?

No non-fingerprinted asset files versions for you. I've noticed this issue in a really painful way: on the production. It isn't documented anywhere, so I assume, that this is a bug (nasty one btw). When you perform:

rake assets:precompile

It generates whole bunch of files, however you might notice, that there's no non-fingerprinted once there. All of them include fingerprints. I've even tried to disable fingerprinting at all with:

config.assets.digest = false

but Rails keeps ignoring that.

My first reaction after I've noticed that, was like that:

Assets stap

I do like digest idea, but there are some libraries (like Ckeditor) that won't work without "clean" file versions. So until it is fixed, I'll be using a simple rake task that I've created:

  require 'ostruct'

  desc 'Creates a non-digest version of all the digest assets'
  task fix_assets: :environment do
    require 'fileutils'
    regexp = /(-{1}[a-z0-9]{32}*\.{1}){1}/

    assets = File.join(Rails.root, 'public', Susanoo::Application.config.assets.prefix, "**/*")
    Dir.glob(assets).each do |file|
      next if File.directory?(file)
      next unless file =~ regexp

      source = file.split('/')
      source[source.length-1] = source.last.gsub(regexp, '.')

      non_digest = File.join(source)
      File.delete(non_digest) if File.file?(non_digest)

      FileUtils.cp(file, non_digest)
    end
  end

This will go through all the assets and will copy fingerprinted versions to non-fingerprinetd once. It should be executed after assets precompilation:

rake assets:precompile
rake fix_assets

ActiveRecord

There's whole bunch things that were changed in ActiveRecord:

All method

All method will now return a new relation instead of Array:

# previously:
News.all.class #=> Array

# in Rails 4
News.all.class #=> ActiveRecord::Relation::ActiveRecord_Relation_News

Thanks to that, we can do chainings on an all method.

Load method

Load causes the records to be loaded from the database if they have not been loaded already. You can use this if for some reason you need to explicitly load some records before actually using them. The return value is the relation itself, not the records. You can treat this a bit as a replacement for all method.

None scopes

None scopes are one smart way to handle privileges management for AR resources (but not only for that!). Sometimes we want to create a method, that returns limited amount of objects based on incoming data. In previous Rails versions we would normally return an empty array if we wouldn’t have any privileges. However that might be troublesome when we're chaining scopes:

class Fancy < ActiveRecord::Base
  def self.resources_for(user)
    user.has_role?(:admin) ? all : []
  end
end

This obviously won't work with chaining (will raise an error):

Fancy.resources_for(current_user).active
# Will raise undefined method `active' for []:Array fir bith cases

In Rails4 we can use none scope that will allow us to chain as many scopes as we want. The none scope is implemented with ActiveRecord::NullRelation. No queries will be performed on the database:

class Fancy < ActiveRecord::Base
  def self.resources_for(user)
    user.has_role?(:admin) ? all : none
  end
end

Now the chaining will work perfectly.

Not query

Let's allow Rails to talk:

News.where.not('title LIKE ?', rejected_title)
News.where.not(title: rejected_title)
# It was in Mongoid for a while and finally we have it in AR also

update in favour of update_attributes

You can use update now instead of update_attributes. No need to worry due: update_attributes will stay with as for a while also.

@news = News.last

# Rails 3
@news.update_attributes(title: 'Rails 3 is quite old')
# Rails 4
@news.update(title: 'Rails 4 is new and shiny!')

Of course they both do the same.

protected attributes are out

Finally! I've never like this idea. It should not be a models responsibility to manage privileges. I will talk about that more in the next part but for know you need to know that Rails 4 moved the parameter sanitization from the model to the controller layer.

ordering for scopes works in a different way

WARNING: THIS HAS BEEN REVERTED TO THE BEHAVIOUR FROM RAILS 3.2!

For more details please see this blog post and this github commit!

I won't even try to count how many times I had to create a scope that looked just like a different one but with a different order. Luckily it ends now! Rails 4 ordering changes the order order :-) Until now any new order has been appended as a last one. This caused troubles sometimes:

class Fancy < ActiveRecord::Base
# Let's assume that this is a scope that is used in many, many places
scope :active, ->{ where(active: true).order('created_at ASC') }
end

I would love to list all the active Fancy objects, but in a different order. I don't want to change that scope, since it is widely used. So what can we do? Probably we would need to create a new similar scope. But not in Rails 4! In Rails 4 orders aren't appended but instead they are prepended, so we can create scopes with default sort order but change it on demand:

class Fancy < ActiveRecord::Base
# Let's assume that this is a scope that is used in many, many places
scope :active, ->{ where(active: true).order('created_at ASC') }
end

# created_at ascending sort
# SELECT `fancies`.* FROM `fancies` WHERE `fancies`.`active` = 1 \
# ORDER BY `fancies`.`created_at` ASC
Fancy.active

# created_at descending sort
# SELECT `fancies`.* FROM `fancies` WHERE `fancies`.`active` = 1 \
# ORDER BY `fancies`.`created_at` DESC, `fancies`.`created_at` ASC
Fancy.active.order('created_at DESC')

First this might cause you a bit of troubles, especially if you're using meta_search or Ransack. You'll need to rewrite most of your search invocations. But in a longer perspective, this change is really good. If you want to pass multiply sorting orders, instead of doing something weird like that:

# This will generate sorting first by title and then by created at
Fancy.all.order('created_at DESC').order('title ASC')

You may want to use this syntax:

# Here order will be from left to right
Fancy.all.order('title ASC', 'created_at DESC')

regexp validation for validates_format_of

After trying to run your Rails app, you may see such an ArgumentError

ArgumentError: The provided regular expression is using multiline anchors (^ or $),
which may present a security risk. Did you mean to use \A and \z,
or forgot to add the :multiline => true option?

If you don't expect multiline incoming data, you need to replace all the "^" with "\A" and all the "$" with "\z". If you expect multiline strings, just specify the multiline: true option. After that, you're ready to go.

auto_explain_threshold_in_seconds is gone

Just remove it from your config file and:

deal_with_it___rainbow_style__by_j_brony-d4cwgad

MySQL strict mode

Not sure if it came with Rails 4 - but I like that! If you encounter such an error:

ActiveRecord::StatementInvalid: Mysql2::Error: Field 'seo_url' doesn't have a default value:
INSERT INTO `texts` (`name`, `seo_url`) VALUES ('name')

You need to change your tables and define default values for columns that cannot be null:

change_column :logs, :action, :string, :limit => 255, :null => false, :default => ''

find_or_initialize_by in favour of find_or_initialize_by_attr1_and_attr2

DEPRECATION WARNING: This dynamic method is deprecated.
Please use e.g. Post.find_or_initialize_by(name: 'foo') instead.

It means that instead of:

Post.find_or_initialize_by_name_and_title(name, title)

You should do this:

Post.find_or_initialize_by(name: name, title: title)

Something is wrong when we inherit not directly from ActiveRecord

Well this is not a feature - more like a bug to me. When you inherit from an abstract class that inherits from AR:

class Abs < ActiveRecord::Base
  self.abstract_class = true
end

class Ebs < Abs
  self.table_name = :ebses
end

and you try to use such an object, you might get an error:

ActionView::Template::Error: Mysql2::Error: Incorrect table name '': SHOW FULL FIELDS FROM ``

Didn't figure that out yet. Unfortunately I had to do a workaround and I've extracted common functionalities into a module that is included in all the classes that were inheriting from my abstract class.

Update: You can find the solution here: http://stackoverflow.com/questions/27914918/ruby-on-rails-rake-throwing-incorrect-table-name-error-after-updating-rails-pr

In general, just don't declare relations in an abstract class.

Upgrading to Rails 4.0 from Rails 3.2 – Test case – Part I (preparations, configuration, gems)

In this articles series, I'll try to cover all the issues that I had, when I was upgrading one of my Rails app from Ruby on Rails 3.2 to Ruby on Rails 4.0.

Preparations - What should we do before upgrading to Rails 4?

  • Upgrade your Ruby version at least to 1.9.3 (I would recommend 2.0)
  • Upgrade bundler
  • Upgrade your application to the most recent Rails 3.2 version
  • Check gems compatibility (you may want to be on edge with few gems (or use Rails 4 branches))
  • Write more tests if you don't have a decent code coverage

The last point is the most important. If you don't have a good code coverage level and you lack tests, upgrading from Rails 3.2 to Rails 4 might be a big problem.

Attributes protected and some other Rails 3 features

Rails team moved a lot of stuff from Rails core to gems. In order to make an upgrade smooth, probably the best solution is to add all the gems into Gemfile and then upgrade given functionalities one by one after successful Rails 4 migration:

gem 'protected_attributes' # https://github.com/rails/protected_attributes
gem 'active_resource' # https://github.com/rails/activeresource
gem 'actionpack-action_caching' # https://github.com/rails/actionpack-action_caching
gem 'activerecord-session_store' # https://github.com/rails/activerecord-session_store
gem 'rails-observers' # https://github.com/rails/rails-observers
# Note that there might be more functionalities that were extracted

Be aware, that some of those gems might not be maintained longer than till Rails 4.1 release!

Upgrading to Rails 4 - Gemfile

First thing that needs to be done, when upgrading to Rails 4 is changing our Gemfile:

gem "rails", '~>4.0.0'
# Remember to require dalli if you're using memcached
gem 'dalli'
# Remember to update any gems that require something special in order to work with Rails 4
gem 'squeel', :git => "git://github.com/ernie/squeel.git"
gem "ransack", :git => "git://github.com/ernie/ransack.git", :branch => 'rails-4'
gem 'simple_form', :git => 'git://github.com/plataformatec/simple_form.git'

Also if you have an assets group, it needs to be removed. You can move the assets gems to a default group:

# group :assets <--- this needs to go away
gem 'coffee-rails'
gem 'sass-rails'
gem 'uglifier'
# end

After updating your Gemfile you can do a

bundle install

and hopefully you're ready for upgrade!

Configuration files - rake rails:update

There are some changes in configuration files (that I will cover), but I would strongly recommend running:

rake rails:update

allow it to overwrite your files and then just add the stuff that you've needed and is not there. IMHO it is way less complex approach, that trying to add all new config options manually.

Rails.root + /config/environments/*.rb

Things that are no longer available and need to be removed from those file:

  • config.whiny_nils = true
  • config.action_dispatch.best_standards_support = :builtin
  • config.active_record.mass_assignment_sanitizer = :strict
  • config.active_record.auto_explain_threshold_in_seconds = 0.5

Things that need to be added (with values appropriate for given environment):

  • config.eager_load = false
  • config.active_record.migration_error = :page_load

Things that need to be changed:

  • config.cache_store = :dalli_store => config.cache_store = :mem_cache_store

Remember to set eager_load in all environments. If not, you'll see following warning:

config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:

  * development - set it to false
  * test - set it to false (unless you use a tool that preloads your test environment)
  * production - set it to true

If you don't remove the auto_explain_threshold_in_second option, you'll see following warning:

DEPRECATION WARNING: The Active Record auto explain feature has been removed.

To disable this message remove the `active_record.auto_explain_threshold_in_seconds`
option from the `config/environments/*.rb` config file.

filter_parameters

In Rails 3 filter_parameters setting was set up in application.rb. In Rails 4 there will be created an initializer for that (config/initializers/filter_parameters.rb):

Rails.application.config.filter_parameters += [:password, :file_value]

So you may consider moving this setting our of your application.rb file.

Secret token (config/initializers/secret_token.rb)

There is a new value for that initializer:

Susanoo::Application.config.secret_token = 'your current token'
Susanoo::Application.config.secret_key_base = 'secret value' # this needs to be added

The secret_key_base is not required but if you don't add it, you'll have a deprecation warning:

DEPRECATION WARNING: You didn't set config.secret_key_base.

Cookies from Rails 3 will be transformed automatically into Rails 4 format but be aware, that this won't work the other way around, so if by any reason you'll want to get back to Rails 3, all the user cookies will be unreadable.

In order to generate a random secret_key value, you can use rake task:

rake secret

This will just generate secret, you need to copy it to this initializer manually!

Rails.root + /config/application.rb

If you had any interactions with routes loading process you need to change config/routes in such a way:

config.paths['config/routes.rb'] # add .rb

Example:

# Load all the routes from routes directory
Dir["#{Rails.root}/config/routes/**/*.rb"].each do |route_file|
  config.paths['config/routes.rb'] << route_file
end

Conclusion

If you have a decent code coverage level and you know what you're doing, upgrade should not be a big problem. At this point, if you're not using any fancy route settings, you should be able to at least start your application:

./script/rails s -u

I'll cover more deprecation warnings and other issues soon.

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑