`

ruby on rails 入门注意事项 3

    博客分类:
  • ruby
阅读更多

参考我前面的博客:

 http://hw1287789687.iteye.com/blog/2288230

 http://hw1287789687.iteye.com/blog/2288267

(1)更新记录的视图

 我原来写的(不成熟):

<div>编辑</div>

<%= link_to "列表", {:action => 'list'} %>&nbsp;
<div>
  <%= form_for :article, method: "PUT", url: {action: "update"} do |f| %>

      <ul>
        <li>
          <label for="">title:</label>
          <input type="text" name="article[title]" value="<%= @article.title %>">
        </li>
        <li>
          <label for="">text:</label>
          <input type="text" name="article[text]" value="<%= @article.text %>">
        </li>
        <li>
          <%= f.submit %>
        </li>
      </ul>
      <input type="hidden" name="id" value="<%= @article.id %>">
  <% end %>
</div>

 

最佳实践:

<div>编辑</div>

<%= link_to "列表", {:action => 'list'} %>&nbsp;
<div>
  <%= form_for @article, method: "PUT" do |f| %>

      <ul>
        <li>
          <label for="">title:</label>
          <%= f.text_field :title%>
        </li>
        <li>
          <label for="">text:</label>
          <%= f.text_field :text%>
        </li>
        <li>
          <%= f.submit %>
        </li>
      </ul>
      
  <% end %>
</div>

 特点:

(a)没有手动指定表单提交的action;

(b)没有显式地给文本框赋值

(c)省略id的隐藏域

(2)创建控制器

 bin/rails generate controller pass

      create  app/controllers/pass_controller.rb

      invoke  erb

      create    app/views/pass

      invoke  rspec

      create    spec/controllers/pass_controller_spec.rb

      invoke  helper

      create    app/helpers/pass_helper.rb

      invoke    rspec

      create      spec/helpers/pass_helper_spec.rb

      invoke  assets

      invoke    coffee

      create      app/assets/javascripts/pass.coffee

      invoke    scss

      create      app/assets/stylesheets/pass.scss

(3)查看路由

 bin/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

(4)创建实体类:

bin/rails generate model Pass title:string username:string  pwd:string description:text status:tinyint

      invoke  active_record

      create    db/migrate/20160403064342_create_passes.rb

      create    app/models/pass.rb

      invoke    rspec

      create      spec/models/pass_spec.rb

      invoke      factory_girl

      create        spec/factories/passes.rb

注意:列与列之间以空格分隔

 因为ruby on rails 是高度的约定优于配置,所以一些细节被隐藏了,比如你看不到form的action属性

1
4
分享到:
评论
Global site tag (gtag.js) - Google Analytics