Search code examples
rubyruby-on-rails-3rubygemsruby-on-rails-pluginsmodels

ruby on rails id not appearing in my model


I'm trying to add basic id number to a title slug

here is my model:

class Post < ActiveRecord::Base
  before_save :title_to_slug

  def title_to_slug
    self.title_slug = "#{id}-" + "#{title}".to_slug
  end

end

.to_slug comes from https://github.com/ludo/to_slug

when i save the new post the title slug has no id at all, the output is "-post-title"


Solution

  • You won't have an id until you save. You could change your before_save hook to an after_save and use update_attribute to set the title_slug.

    One other thought. Leave the id out of the slug and add it in with your getter:

    def title_slug
      "#{id}-#{read_attribute(:title_slug)}"
    end