开发者

ruby on rails id not appearing in my model

开发者 https://www.devze.com 2023-02-08 10:38 出处:网络
I\'m trying to add basic id number to a title slug here is my model: class Post < ActiveRecord::Base

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_sl开发者_高级运维ug 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"


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消