Getting Started with Rails (1)

按照官网http://guides.rubyonrails.org/getting_started.html上学习了一下例子。在过程中有很多刚开始没理解的地方,写下来。

 

首先,建立了一个resources :articles。然后rake routes出现了如下

$ rake routes
      Prefix Verb   URI Pattern                  Controller#Action
    articles GET    /articles(.:format)          articles#index
             POST   /articles(.:format)          articles#create
new_article GET    /articles/new(.:format)       articles#new
edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy
        root GET    /                            welcome#index
 
这是已经建立的所有路由,四种url和不同的verb一起对应了七个方法。
这里要注意一下rails是按照顺序来匹配url的,比如说后面的链接
<%= link_to 'Back', articles_path %>,都是返回到index页面。但是articles_path对应的是/articles,对应了两个页面index和create,
为什么不是返回到create页面呢。因为index页面排序在前面。后面的article_path返回show页面也是同理。
 
测试方法:写一个create.html.erb文件,然后让模型中create方法不指向其他页面(例如注释掉create中所有内容),接着在config/routes.rb中resources :articles之前加上get 'articles' => 'articles#create'。那么就会优先转到create页面了。
 
 
关于new里的表单<%= form_for :article do |f| %>,这句话的意思就是为:article建立了一个表单,这个symbol的命名和这个应用没有关系,之前还以为因为resources :articles的缘故,其实它随便换成什么都可以。后面可以用这个标识来从这个表单里面取值。
 
关于redirect_to @article这种指向一个实例的用法和 <%= link_to 'Edit', edit_article_path(@article) %>这种实例的路径的用法,我觉得是应为:id这个属性是唯一的来标识一个实例,所以实例和:id可以用来替换的。当使用实例时,有时候根据需要可以默认自动转化为:id。所以redirect_to @article会指向controller/:id。
edit_article_path(@article)对应着edit_article_path(:id),指向controller/:id/edit
 
具体来说:redirect_to @article
     redirect_to  article_path(@article)
     redirect_to  article_path(@article.id)
            redirect_to  /articles/#{@article.id}
    都是等价的
    
 
 
posted @ 2014-04-26 03:26  smallbottle  阅读(241)  评论(0编辑  收藏  举报