How to correctly implement the ability to choose the type of link, that is, to be able to change the format of the link, for example, as in wordpress : url/post/id urp/post/title url/date/title url/title

Whether the correct solution is to make the settings table with the url_pattern string containing, for example, the variant number or the required format. And to make a helper in the application, which will receive the value of the url_pattern parameter from the database (or from a global variable) and use the case to substitute the necessary link format?

    1 answer 1

    Well, if you want the recording to respond to any of these URLs at the same time, then I would do something like this (the code is not tested and intentionally simplified):

    In routes:

     get 'post/:id' => 'posts#show', as: :by_id_or_title get 'date/:date' => 'posts#show', as: :by_date 

    posts_controller:

     def show @post = Post.find_by_title_or_id(params[:id])||Post.find_by_date(params[:date]) end 

    models / post:

     def self.find_by_title_or_id(id) return nil if id.blank? find_by(title: id)||find_by(id: id) end def self.find_by_date(date) return nil if date.blank? find_by(date_field: date) end 

    Create links like this: link_to 'Link by date', by_date_path( @post .date_field)

    View routes: rake routes. Read more: http://rusrails.ru/rails-routing

    When working with dates, pay attention to the format, so that what you betray to the helper coincides with what you are looking for in the database.

    • But this is how to handle the paths, and how would you make the ability to change the format of links for to_link. The helper that receives the parameter and through the case displays the desired type of url will be normal or can you think of a better one? - batazor
    • the "as:: by_date" directive in routes will create a helper. It works like this: link_to 'Link by date', by_date_path (@ post.date_field) - mayar
    • Updated the answer ... - mayar