I
I
Infinite2016-10-11 20:22:07
Ruby on Rails
Infinite, 2016-10-11 20:22:07

How to make URL with date like on Meduza?

How to make a URL like this https://meduza.io/feature/2016/10/11/sgorevshiy-fl... ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Sidorov, 2016-10-12
@morr

The to_param method in the ActiveRecord model is responsible for generating the url.
For the meduza example, the to_param method would look something like this

class Article < ...
  # ...
  def to_param
    "#{created_at.year}/#{created_at.month}/#{created_at.day}/#{transliterated_title}"
  end
  # ..
end

But that alone is not enough to get things going. The controller now needs some kind of mechanism that can follow the line "2016/10/11/sgorevshiy-flagman-perezhivet-li-samsung-proval-s-galaxy-note-7".
And here there are two options.
1. In the first option, in the to_param method, id is added to the string like this
def to_param
  "#{created_at.year}/#{created_at.month}/#{created_at.day}/#{id}-#{transliterated_title}"
end

or like this
def to_param
  "#{created_at.year}/#{created_at.month}/#{created_at.day}/#{transliterated_title}-#{id}"
end

In this case, in the controller, we extract the id from the string and look for the model in the database using it.
2. In the second option, a field is added to the model, which is usually called either permalink or slug. And in the model, this field will be filled in before_save callback.
before_save :update_slug

private

def update_slug
  self.slug = to_param
end

After that, in the controller, you can search for the model by string.
Personally, I prefer the first method, because. it is simpler, especially if id is placed at the very beginning of the line like this
def to_param
  "#{id}-#{transliterated_title}"
end

Here, the model search turns into a regular find.
To automate the second method, there are permalink and friendly_id gems .

P
Pavel Grudinkin, 2016-10-11
@Hunt666

form part "sgorevshiy-flagman...." will help gem friendly id
About the date this should help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question