rails基础汇总

作者: 程序员小哥哥 | 来源:发表于2017-11-17 16:38 被阅读64次

    一:ruby on rails, Router路由

    前言:ruby学习掌握20%就可以开始rails的学习了,知道ruby的Symbol、block和@变量即可。

    1.在config的routes.rb中写上resources :students,rails会默认生成7种路由(这里假设students)

    GET  /students  index    显示 student的列表页
    
    GET  /students/newnew显示 student的新建页面
    
    GET  /students/3      show      显示id是3的student
    
    GET  /students/3/edit  edit      显示student(id=3)的编辑页面
    
    PUT  /students/3      update    对i =3的student进行修改
    
    POST /students        create    对students进行创建
    
    DELETE  /students/3    destroy  对 id=3的 student 进行删除操作
    

    我们这里可以在项目中敲打rake routes来查看当前项目下所有的路由:

    系统输出版:

    POST    /students(.:format)            students#create
    
    new_student GET      /students/new(.:format)        students#new
    
    edit_student GET      /students/:id/edit(.:format)    students#edit
    
    student GET      /students/:id(.:format)        students#show
    
    PATCH    /students/:id(.:format)        students#update
    
    PUT      /students/:id(.:format)        students#update
    
    DELETE  /students/:id(.:format)        students#destroy
    

    清晰整理版:

    url      请求方式  对应的url表达式                controller#action
    
    students_path  POST    /students(.:format)          students#create
    
    new_student_path  GET      /students/new(.:format)        students#new
    
    dit_student_path  GET      /students/:id/edit(.:format)    students#edit
    
    student_path  GET      /students/:id(.:format)        students#show
    
    student_path  PATCH    /students/:id(.:format)        students#update
    
    student_path  PUT      /students/:id(.:format)        students#update
    
    student_path  DELETE  /students/:id(.:format)        students#student
    

    说明:url的*_path都可以换成*_url,通过url路径我们可以实现action的跳转

    2.如果想额外增加自己想要增加的action怎么办呢?我们现在知道在resources :会默认生成7中路由,我们如果单独增加,比如想增加list这个action,

    我们可以这样写:

    routes.rb:

    resources :students do
    
      collection do
    
        get :list
    
      end
    
    end
    
    controller:
    
    class StudentsController < ApplicationController
    
      def list
    
      end
    
    end
    

    说明: def list这个list就是action

    3.实现页面的跳转

    list.html.erb:

    <%= link_to '添加学生信息', new_student_path %>
    

    new.html.erb:

    <%= link_to '跳转到所有学生的信息', list_students_path %>
    总结:学完路由之后要能看到resources能人肉出7种路由,并能知道对应的action和url
    

    有时间多看:

    英文版:http://guides.rubyonrails.org/routing.html

    中文版: http://guides.ruby-china.org/routing.html

    二:ruby on rails, migration(数据库迁移)

    使用rails的migration之前先配置以下几步

    1.在config/database.yml配置MySQL

    这里的意思是这是开发模式下的数据库配置,可以选择的是:development, test, production

    这里的意思是这是开发模式下的数据库配置,可以选择的是:development, test, production

    development:
    
      # 表示数据库的驱动
    
      adapter: mysql2
    
      # 数据库的名字
    
      database: db_name
    
      # 数据库的用户名
    
      username: root
    
      # 表示密码
    
      password: admin
    
      # 数据库的ip地址
    
      host: localhost
    

    2.修改Gemfile

    这里修改之前先把默认的sqllite删掉,不加'0.3.17'会默认生成最高版本,这里不需要,按下面的配置即可。

     gem 'mysql2', '0.3.17'
    

    3.执行命令$ bundle install

    这里相当于Java的maven,可以为项目添加所需的gem

    4.创建数据库

    $ bundle exec rake db:create
    

    这是,你会发现数据库已经创建好了

    5.执行命令$ rails generate migration CreateTableName来创建migrate文件

    例如:$ rails g migration CreateStudents(migration可以省略成g)

    我们会发现在项目的db/migrate会多出一个文件,打开,编辑。

    #db/migrate/20161202100861_create_students.rb
    
    class CreateStudents < ActiveRecord::Migration
    
      def up
    
        create_table :students do |t|
    
          t.string :name
    
          t.timestamps
    
        end
    
      end
    
      def down
    
        drop_table :students
    
      end
    
    end
    
    

    解释:

    up的意思是从过去,往未来的时间方向上发展

    down的意思是在时间上倒退

    因为它可以移过来,再移回去.在不断的up/down中,数据库实现了迁移,这就是这个名字的由来,每个文件都有时间戳。

    6.执行命令$ rake db:migrate

    这样查看数据库就会发现学生表已经创建成功了,而且里面会有name、create_up、update_up这三个列

    7.想要回滚执行命令$ rake db:rollback

    一般在商业项目中很少用rollback,比如你修改表结构,一般会执行$ rake dbLmigrate

    8.up down和change的区别

    如果你用rails 4.x 来创建的话,得到的migration ,一般没有up, down 方法。因为,rails 非常智能,能自动的把up和down方法合并成change这个方法。

    如果up方法中,是create_table, 那么,rails就会自动判断出,在down 方法中,就用drop_table。但是因为是项目中,我们一般也不会删除表,所以

    用的多的是change,不过有时候rails无法进行判断,还是推荐用up down方法。

    三:ruby on rails, form表单对象

    前言:我们都知道浏览器传递给服务器可以传三种数据类型,在rails中也是一样的。

    • 1.字符串
    • 2.数组
    • 3.hash

    1.在rails中使用form_for
    如果我有一个对象,叫 article, 它有两个属性: title, content。

    <% form_for @aritcle do |f| %>  
      <%= f.text_field :title %>  
      <%= f.text_field :content %>  
    <% end %> 
    

    解释:do和end是一个代码块,而f代表这个表单对象。
    注意:这里的f.text_field使用之后,如果没有值那就是空,有值得话(修改操作),就会显示默认值。
    相当于生成了下面的,这里我给两个标签里都写入了内容:

    <form action='/articles'  method='post' >  
      <input type='text' name='article[title]' value= '我是标题' />  
      <input type='text' name='article[content]' value= '我是正文' />  
    </form>
    

    传递到后台:

    {  
        article: {  
            title: "我是标题",  
            content: "我是正文"  
        }  
    }  
    

    2.是传递的hash,这样我在后台接收:

    Article.create params['article'] 
    

    3.这里介绍下form_for
    form_for是个方法,有三个参数
    form_for(record, options = {}, &block)

    <% form_for @aritcle do |f| %>  
    

    就比如我上面写的代码,record就是@article,options就是{},所以被省略掉了,block是代码块

    四:ruby on rails, Model的关联

    前言:
    在学习model关联之前,首先要牢记一下几点:
    1.关联关系,两端都要写好,否则会出现初学者看不懂的错误。而且对于理解代码,非常有好处。
    2.model的名字是单数,controller是复数。
    3.blong_to后面必须是单数,而且必须是小写。has_many后面必须是复数。

    1.一对多
    例如:
    王妈妈有两个孩子,小明和小亮。可以说,王妈妈,有多个孩子。也可以说:小明,有一个妈妈;小王,有一个妈妈。我们一般在设计表的时候,是这样设计的:
    mothers表中id和name
    sons表中有id和name
    为了增加逻辑关系,主外键关系,会在多的一方,增加一列,所以sons表中有三列,id和name和mother_id(对应了mothers表的id)
    普通SQL:

    select test_associate.mothers.name from test_associate.mothers inner join test_associate.sons on sons.mother_id = mothers.id where sons.name = '小李' 
    

    ruby代码:

    class Mother  
      has_many :sons  
    end  
    
    class Son  
      belongs_to :mother  
    end  
    

    解释:一个妈妈又多个孩子,一个儿子属于一个妈妈。
    我们在rails console可以测试下:

    xiao_wang = Son.first  
    mom = xiaowang.mother
    

    这个 .mother 方法就是由 class Son的belongs_to :mother这句话生成的。
    也就是相当于转换成了一下的sql语句:

    select * from mothers  
        join sons  
        on sons.mother_id = mothers.id  
        where sons.id = 1
    

    详细解释:
    A:belongs_to :mother
    B:belongs_to :mother, :class => 'Mother', :foreign_key => 'mother_id'
    A=B
    这个就是Rails最典型的根据惯例来编程,声明哪个表对应的是哪个class,再在class之间声明好关联关系。
    1.belongs_to :mother, rails就能判断出: mothers 表,是一的那一端。 而当前class 是: "class Son", 那么rails 就知道了 两个表的对应关系。
    2.:class => 'Mother', 表示, 一的那一端, 对应的model class是Mother. 根据rails的惯例, Mother model对应的是 数据库中的 mothers 表。
    3.:foreign_key => 'mother_id', rails就知道了, 外键是 'mother_id'. 而一对多关系中, 外键是保存在 多的那一端(也就是 sons, 所以说,在 sons表中, 必须有一个列, 叫做: mother_id )

    所以, 这个复杂的SQL 条件就齐备了, 可以生成了。
    上面的ruby代码,配置好之后, 就可以这样调用:
    son = Son.first
    son.mother  # .mother方法,  是由 class Son 中的 belongs_to 产生的。
    mother = Mother.first
    mother.sons   # .sons 方法,  是由 class Mother 中的 hash_many  产生的。
    

    2.:
    一对一,比较简单,也不常用,这里不介绍。(老公和老婆)

    3:
    多对多

    例如:
    一个学生,有多个老师,(学习了多门课程)
    一个老师,可以教多个孩子(教一门课程,但是有好多学生来听这个课程)
    我们往往会这样做:
    students有id和name两个字段
    teachers有id和name两个字段
    放在任何一个表中都不合适,这是我们需要一张中间表,也就是桥梁表。
    lessons有id和name和student_id和teacher_id
    原始SQL:

    select teachers.*, students.*, lessons.*  
        from lessons from teachers ,  
        join teachers  
        on lessons.teacher_id = teachers.id  
        join students  
        on lessons.student_id = students.id   
        where students.name = '小王'  
    

    Ruby代码:

    class Student  
      has_many :lessons  
      has_many :teachers, :through => :lessons  
    end  
    

    提示:has_many :teachers, :through => :lessons 相当于

    has_many :teachers, :class => 'Teacher', :foreign_key => 'teacher_id', :throught => :lessons
    
    class Teachers  
      has_many :lessons  
      has_many :students, :through => :lessons  
    end 
    

    查看小王的老师有哪些,同上面的原始SQL语句。

    Student.find_by_name('小王').teachers 
    

    相关文章

      网友评论

        本文标题:rails基础汇总

        本文链接:https://www.haomeiwen.com/subject/syfjvxtx.html