Routes The beginning

    Routes in rails are a very important thing. But for the time being, you can not even pay attention to them. Especially if you use the scaffold command, which automatically prescribes everything. But at some point there is a need to create non-standard routes. This means it's time to get into the routes.rb file in the config folder of your project.

    What are routes


    Routes are a system of routes (paths, urls) on your site. Thanks to the routes, we can have links that are beautiful and clear to users. By entering a link like mysite.ru/articles/2008/november/13 we get all the articles for November 13, 2008, and by the link mysite.ru/shop/shoes we get the shoe catalog from your store. With all this, the directory structure of the site does not change. At any time, we can change the routes without touching the location of the files themselves. But for all this to work, we need to configure the routes.

    To practice


    Let's create a test project with which we will be a shaman. (If this is your first time doing this, you can discuss in the comments the process of installing the rail and creating the application). Okay The project was created and we entered the working folder. Immediately attack the routes: this command will give you two lines of standard routes. This means that any URL will now be parsed by these two rules. : controller is controller =). This is the MVC component , which most often acts as an intermediary between the View (HTML) and the Model (database, say). It will be clearer further, but most likely you already know what it is. : action is the called method of the controller. The controller usually has many methods.

    rails routes
    cd routes




    rake routes


    /:controller/:action/:id
    /:controller/:action/:id.:format





    : id - if I do not explicitly indicate a ban on creating id, then by default any model (database table) is created with the id field. Therefore, any element of the model has id. And when you want to delete / edit / anything to do with any particular element of the model, you must pass this same id to the controller.

    Okay Let us create a news magazine. To do this, we need:
    - The news table in our database (Model). In the database we will store the title of the article (title), the author of the article (author) and the article itself (article)
    - A set of methods for working with the database (Controller)
    - HTML forms for entering, editing, reading news (Presentation)
    We can create everything it is separately. But now we will simplify our task and use the scaffold function to generate a pack of ready-made files.

    ./script/generate scaffold Magazine title:string author:string article:text

    We just created all of the above (as well as Helpers, about which some other time). The scaffold team itself created the necessary routes. Rake routes command again and a bunch of new routes will fall out
    magazines GET / magazines {: controller => "magazines",: action => "index"}
    formatted_magazines GET /magazines.:format {: controller => "magazines",: action => "index"}
    			                      POST / magazines {: controller => "magazines",: action => "create"}
    			                      POST /magazines.:format {: controller => "magazines",: action => "create"}
    new_magazine GET / magazines / new {: controller => "magazines",: action => "new"}
    formatted_new_magazine GET /magazines/new.:format {: controller => "magazines",: action => "new"}
    edit_magazine GET / magazines /: id / edit {: controller => "magazines",: action => "edit"}
    formatted_edit_magazine GET /magazines/:id/edit.:format {: controller => "magazines",: action => "edit"}
    magazine GET / magazines /: id {: controller => "magazines",: action => "show"}
    formatted_magazine GET /magazines/:id.:format {: controller => "magazines",: action => "show"}
    			                      PUT / magazines /: id {: controller => "magazines",: action => "update"}
    			                      PUT /magazines/:id.:format {: controller => "magazines",: action => "update"}
    			                      DELETE / magazines /: id {: controller => "magazines",: action => "destroy"}
    			                      DELETE /magazines/:id.:format {: controller => "magazines",: action => "destroy"}
    

    Now we will start the server and play with the log. But first, we will create our database and start the migration. Our magazine is now available at localhost : 3000 / magazines. Create a couple of new articles. Back to the route table above. The first column is named routes. They are very comfortable. There are several options now to make a link to create a new article. Open the app / views / magazines / index.html.erb file - this is the view for the index method in the magazines_controller controller. At the bottom, let's add some code.

    rake db:create
    rake db:migrate
    ./script/server









    <%= link_to 'Новая статья', :action => 'new' %>
    <%= link_to 'Новая статья', '/magazines/new' %>
    <%= link_to 'Новая статья', new_magazine_path %>
    <%= link_to 'Новая статья', new_magazine_url %>


    The most correct is to use the last two methods. The difference is that url returns the full link (http: // localhost: 3000 / magazines / new), and path only the path (/ magazines / new). Why is it better to use named routes? A named route is a variable by changing which you change all the links that use this route. Writing paths by hand is not recommended at all, if it does, it’s better to write: action => 'new' (often there are not enough named routes for all occasions, so this option is very common).

    The second column of the table is the query method. One and the same link, but with a different method leads to different controller methods. For example, in the same app / views / magazines / index.html.erb:
    <%= link_to 'Show', magazine %>
    <%= link_to 'Destroy', magazine, :method => :delete %>

    In the first link, a default GET request is executed (you can omit the link in the link: method =>: get), and in the second the method: delete is sent. And the magazine link remains the same in both cases.

    The third column is actually the links that we get in HTML. The last column is the correspondence of the links to the controller and the method. As already mentioned above, any link can be represented as a pair: controller,: action (well, sometimes: method).

    <% = link_to 'Link to another controller from the magazines controller',: controller => 'blogs',: action => 'show',: id => '1',: method => 'GET'%>
    So we get link to the blog with index 1. (Here the method: get could be omitted)
    <% = link_to 'Link to the controller’s native method',: action => 'show',
    Link to the article with index 1. The controller and HTTP method in this case do not need to be specified, since GET is executed by default, and the controller, if not specified, runs the same.

    Now open the file config / routes.rb (you can delete all commented text) The scaffold command inserted the first line. This line added to us a bunch of routes, which we observed above. If you just type localhost: 3000, you will be taken to the welcome page. Let's fix it. Now, from the public folder, delete index.html and going to localhost : 3000 you will get directly to where you want =). In addition, if you look at all the rake routes, you will see a new named root route. And in the menu you can make a link to the "Main" view:

    map.resources :magazines
    map.connect ':controller/:action/:id'
    map.connect ':controller/:action/:id.:format'






    map.root :controller => 'magazines'



    <%= link_to 'Главная', root %>

    And you can always, without prejudice to links, be able to change the home page, say, to your map.root store: controller => 'shop'

    II level


    Actually having created root, you created the first named route with your own hands.
    Let's create a named route " localhost : 3000 / zhurnal". We do not want bourgeois 'magazines', we want 'zhurnal'!

    map.zhurnal '/klevi_zhurnal/:id', :controller => 'magazines', :id => nil

    So, we created the named zhurnal route, the URL of which will look like localhost : 3000 / klevi_zhurnal, and it will receive content from the magazines controller. If we try to read an article now, like localhost : 3000 / klevi_zhurnal / 1, then we will break. We’ll make a few changes in our route:

    map.zhurnal '/klevi_zhurnal/:action/:id', :controller => 'magazines', :action => 'index', :id => nil

    What does all this mean:
    - URL of the form / klevi_zhurnal / will be worked out: controller => 'magazines',: action => 'index',: id => 'nil' - that is, we will get an index page (index.html.erb)
    - / klevi_zhurnal / 1 will spit out an error that action '1' does not exist (look at the sequence of passing the argument in the route)
    - / klevi_zhurnal / show will say that no ID is specified
    - / klevi_zhurnal / show / 1 - will give you an article with ID = 1 (if it exists, of course)
    - / klevi_zhurnal / edit / 1 - will display the edit form for this article The

    truth is now the links themselves look a little harder:
    Instead of <% = link_to 'All articles', magazines_path%> will be <% = link_to 'All articles', zhurnal_path%>
    Instead of <% = link_to 'Article number 1', magazine_path ('1')%> will be <% = link_to 'Article number 1', zhurnal_path (: action => 'show',: id => '1' )%>

    Note thatthat for a better understanding of the routes, the plural / singular system is introduced:
    show all articles magazines_path,
    show a separate article: magazine_path.
    Damn - not the right word at all =). If we had everything called Article:
    index => articles_path, show => article_path (: id)

    Now let's create a new method.
    Open app / controllers / magazines_controller.rb
    Add a method there This method simply returns a random article. Let's try to call it: localhost : 3000 / magazines / random We get an error - it requires an ID from us. Why? Because the standard route implies a route of the form: controller /: action /: id. Let's try to call the route according to the rules: localhost : 3000 / magazines / random / 1230492

    def random
    offset = rand(Magazine.count :all)
    @magazine = Magazine.find(:first, :offset => offset)
    render :action => 'show'
    end






    A record with this ID does not exist - but it works! Since we do not use ID in our method at all, it doesn’t matter for us what nonsense we will write there.
    Now let's still try to make the correct Route type localhost : 3000 / magazines / random /
    To this end, there is an option: collection => {: action = >: HTTP_method}
    Our: action is: random, method -: get
    get

    map.resources :magazines, :collection => { :random => :get }

    now everything works! =)

    This ends the introduction. More sophisticated methods of perversion await us further). But not today.
    Thank you for taking the time to read the article). Ryan Bates Screencast

    APIs

    Also popular now: