2

I have a simple blog engine using Rails and Mongoid ORM.

I have 2 models in the blog, 'Article' and 'Url'. The Article model contains all of the post content, and the Url class is the generator function that takes the slug of the Article and creates a Short URL for it.

E.g. my-sample-blog-post -> ai3n etc. etc.

The problem is I am having problems linking the two. I can't embed the URL class in the Article class either.

My question is, can I generate a Short URL on the fly, as the post is created, inside the Article model? The Article model already uses Mongoid::slug to give me nice post slugs, but I also need short URLs for each post.

Any help on this would be much appreciated.

Smith
  • 21
  • 1

1 Answers1

0

I think you could probably use an after create callback to generate the short url and then store it in a field inside the Article model.

Something like this:

class Article

  field :title
  slug  :title
  field :short_url

  after_create :generate_short_url

  def generate_short_url
    self.short_url = shorten_it(self.slug)   # assuming you implement shorten_it 
    self.save
  end
end
pgaspar
  • 143
  • 1
  • 8