Kurama Kurama - 7 days ago 5
Ruby Question

How to better give a name to the main image file for an article?

I have a single main picture associated with each article on my blog. There's no need to store in a database the name of a main picture because it can infered from either an article id or article url. Article, indeed, has an id and pretty url such as "my-article-about-something". I wonder, what's the better way to name the main pictures for each article: "#{article.id}.jpg" or "#{article.friendly_url}.jpg". They both will work but what if, for example, I'll have to restore a database on a new server? The IDs might be lost. Or maybe there're other downsides. What would you recommnend?

Answer

You can generate unique token for every article and use it in an image's name. This token will be never changed after moving database and all your image's will be unique. Image name will be :token-:friendly_url

Migration code

add_column(:articles, :token, :string, limit: 20)
add_index(:articles, :token, unique: true)

Add new column token and put add the code your article model:

before_validation :generate_token, on: :create

private

def generate_token
  self.token = SecureRandom::hex(6)
  generate_token if self.class.exists?(token: self.token)
end
Comments