Tag: gem

ActiveRecord and FriendlyId: slug not generated when field set with before_validation callback

FriendlyId is an awesome gem for slugging and permalinking for Active Record. It works like a charm except one case: when you set friendly_id field in a before_validation callback.

Here's an example:

class User < ActiveRecord::Base
  extend FriendlyId

  friendly_id :login, use: %i( history finders )

  before_validation :set_login

  def set_login
    # This weird method will just generate a random string
    self.login = (0...8).map { (65 + rand(26)).chr }.join
  end
end

User.new.save!
User.last.login #=> 'bhkcjvrd'
User.last.to_param #=> user id
User.last.slug #=> ''

It happens because FriendlyId uses a before_validation callback to set a slug. This method is invoked before any before_validation callbacks that you define in your class.

To fix this you can either invoke friendly_id after you set your before_validation callbacks, or you can just prepend your method before friendly_id:

class User < ActiveRecord::Base
  extend FriendlyId

  friendly_id :login, use: %i( history finders )

  before_validation :set_login
    prepend: true

  def set_login
    # This weird method will just generate a random string
    self.login = (0...8).map { (65 + rand(26)).chr }.join
  end
end

User.new.save!
User.last.login #=> 'bhkcjvrd'
User.last.to_param #=> 'bhkcjvrd'
User.last.slug #=> 'bhkcjvrd'

Sinatra and Kaminari without any views and without padrino-helpers gem

If you have an app that doesn't have any views (for example it only responds with JSON) you still may want to use excellent Kaminari gem for paginating big data sets. Unfortunately even when you work only with JSON and you don't need any views helpers, you will still get this warning:

[!]You should install `padrino-helpers' gem if you want
to use kaminari's pagination helpers with Sinatra.
[!]Kaminari::Helpers::SinatraHelper does nothing now...

so to get rid of this, you have to add:

gem 'padrino-helpers'

to your Gemfile (even when you don't need it).

Luckily, there's a better way to do this. Add Kaminari to your Gemfile that way:

gem 'kaminari', require: %w( kaminari kaminari/hooks )

and then, either create a config/initializers/kaminari.rb or directly in your app.rb put this:

# Initialize the Kaminari gem
::Kaminari::Hooks.init

This will initialize Kaminari without requesting padrino-helpers.

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑