ruby on rails id not appearing in my model

199 views Asked by At

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"

2

There are 2 answers

0
cam On BEST ANSWER

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
0
Dylan Markow On

Records aren't assigned an ID until they've been saved to the database. You'll need to save the record first, and then add the title slug once it's been saved using an after_save or after_create callback instead.