Ruby on Rails 學習筆記

一、建立新項目simple_cmshtml

rails new simple_cms -d mysql

二、在/config/database.yml中配置項目數據庫信息mysql

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: anuo
  password: xxxxxx
  host: localhost

development:
  <<: *default
  database: simple_cms_development

三、使用rake db:schema:dump, 能夠從如今的數據庫建立schema文件。執行此命令後生成文件:/db/schema.rbweb

四、使用瀏覽器訪問項目redis

  • Start web server  rails s
  • 瀏覽器訪問: http://localhost:3000/

五、生成控制器和視圖sql

  rails generate controller demo index: 生成名爲demo的controller以及index的視圖數據庫

  

  

   routes.rb瀏覽器

  

  

六、服務器請求:瀏覽器發送請求,當在public裏面存在與請求路徑一致的文件時,直接返回該文件,若是不存在,則須要訪問rails 服務。
bash

  

七、路由服務器

  路由類型架構

    Simple Match Route:

      eg:get 'demo/index'  match "demo/index", :to => "demo#index", :via => :get

    Default Route Structure:  :controller/:action/:id  

      eg: GET /student/edit/52  StudentController ,edit action ,id=52

    Default Route:

      eg: get ':controller(/:action(/:id))'  match   ':controller(/:action(/:id))', :via => :get

    Root Route:

      match "/" , :to => "demo#index", :via => :get

八、Render a template

    Render template Syntax

      render(:template => 'demo/hello')

      render('demo/hello')

      render('hello')

九、Redirect Actions

    redirect_to( :action => 'hello')

    redirect_to(:controller => 'test', :action => 'test') #跳轉到testcontroller的test action

    redirect_to("https://www.baidu.com")

    會改變瀏覽器的訪問地址

十、View templates

十一、instance variables

  def hello
      @array = ['Achris','Anuo','Janey','Monic','Alen']
      render('hello')
  end

 

<% @array.each do |n|%>
    <%= n %>,
<% end %>

 

十二、Links

<a href="/demo/hello">Hello page 1</a><br>

<%= link_to('Hello page 2',{:action => "hello"}) %><br>

<%= link_to('Test test page',{:controller => 'test',:action => "test"}) %><br>

1三、URL parameters

  在index界面

<%= link_to('Hello page with parameters',{:action => "hello", :id => 20, :page => 5}) %><br>

 

 

  在democontroller hello方法裏面對參數處理:

 def hello
      @array = ['Achris','Anuo','Janey','Monic','Alen']
      @id =params['id']
      @page = params[:page]
      render('hello')
  end

  在hello.html.erb裏面參數使用

ID: <%= @id%><br>
ID:<%= params['id'] %><br>
Page:<%= params[:page] %><br>
<!--參數默認是string,進行數學計算時須要轉化no implicit conversion of Fixnum into String-->
nextPage: <%= params[:page].to_i + 1 %><br>

 

1四、Generate migrations

rails generate migration DoNothingYet

1五、Generate models

  rails generate model User

  

 

  20170320090551_create_users.rb內容(修改)

class CreateUsers < ActiveRecord::Migration[5.0]

  def up
    create_table :users do |t|
      t.column "first_name", :string, :limit =>25
      t.string "last_name", :limit => 50
      t.string "email", :default => '', :null => false
      t.string "password", :limit =>40
      t.timestamps

      #t.datetime "created_at"
      #t.datetime "uploaded_at"
    end
  end

  def down
      drop_table :users
  end
end

  

  

1六、Run migrations

  rails db:migrate

  

  

  

 

  

  

  回滾(撤回):rails db:migrate VERSION=0

   

            

  

  

  查看數據庫版本:rails db:migrate:status

  

  rails db:migrate VERSION=20170320090551

  

   

1七、Migration methods

    

    

    

 例子

  rails generate migration AlterUsers

  

  20170320090551_create_users.rb內容:

  

class AlterUsers < ActiveRecord::Migration[5.0]
  def up
      rename_table("users","admin_users")
      add_column("admin_users","username", :string, :limit =>25, :after => "email")
      change_column("admin_users","email", :string, :limit =>100)
      rename_column("admin_users","password","hashed_password")
      puts "****Adding an index****"
      add_index("admin_users","username")
  end

  def down
      remove_index("admin_users","username")
      rename_column("hashed_password","password")
      change_column("email", :string, :default => '', :null => false)
      remove_column('admin_users',"username")
      rename_table("admin_users","users")

  end
end

   rails db:migrate

    

1八、Solve migration problems

    當執行錯誤的時候,解決辦法:修改migrate file ,註釋出錯文件中已執行的語句,再次執行rails db:migrate  ,當down時,相似

1九、Challenge Migrations for the CMS

  

   rails generate model Subject

   

   rails generate model Page

   

   rails generate model Section

   

   20170321014824_create_subjects.rb

   

   20170321014839_create_pages.rb

   

   20170321014855_create_sections.rb

   

   rails db:migrate

   

20、撤回到以前版本

   rails db:migrate:status

   

   rails db:migrate VERSION=20170320100921

   

2一、ActiveRecord and ActiveRelation

Active Record 是 MVC 中的 M(模型),負責處理數據和業務邏輯。Active Record 負責建立和使用須要持久存入數據庫中的數據。Active Record 實現了 Active Record 模式,是一種對象關係映射系統。

Active Record 模式出自 Martin Fowler 寫的《企業應用架構模式》一書。在 Active Record 模式中,對象中既有持久存儲的數據,也有針對數據的操做。Active Record 模式把數據存取邏輯做爲對象的一部分,處理對象的用戶知道如何把數據寫入數據庫,還知道如何從數據庫中讀出數據。

對象關係映射(ORM)是一種技術手段,把應用中的對象和關係型數據庫中的數據錶鏈接起來。使用 ORM,應用中對象的屬性和對象之間的關係能夠經過一種簡單的方法從數據庫中獲取,無需直接編寫 SQL 語句,也不過分依賴特定的數據庫種類。

用做 ORM 框架的 Active Record提供了不少功能,其中最重要的幾個以下:

一、表示模型和其中的數據;

二、表示模型之間的關係;

三、經過相關聯的模型表示繼承層次結構;

四、持久存入數據庫以前,驗證模型;

五、以面向對象的方式處理數據庫操做。

   

    

2二、Model naming

  已經講users表更名爲admin_users,有兩種方法讓model與table掛鉤:一、在user.rb文件中self.table_name="admin_users";二、將user.rb更改成admin_user.rb,更改class名User爲AdminUser。

2三、Model attributes

2四、Create records

  方法1:

    1)subject1=Subject.new

    

 

    2)subject1.name="First Subject"

    

 

    3)subject.save

    

  方法1的前兩個步驟能夠異步到位: subject =Subject.new(:name => "First Subject",:position => 1, :visible => true)

  方法2:

    1)subject=Subject.create(:name => "Second Subject",:position => 2, :visible => true)

    

2五、Update records

  方法1: find/setValue/save

    1) subject =Subject.find(1)

     

    2)subject.name="Initial Subject"

     

    3) subject.save

     

 

  方法2:Find/setValue and save

    1)subject =Subject.find(2)

     

 

    2)subject1.update_attributes(:name => 'Next Subject', :visible => false)

     

 

2六、Delete records

  方法:Find/Destroy

     準備工做先建立一個subject : Subject.create(:name => "Bad Subject")

     

 

      1)subject=Subject.find(3)

      2) subject.destroy

     

     subject.destroy以後,記錄不存在在數據庫,可是對象subject仍然存在在應用中,可是不能更改對象subject的任意值。

     

     

      

 

2七、Find records

   Primary key finder :Subject.find(id) ,當根據id找不到數據時報錯ActiveRecord::RecordNotFound: Couldn't find Subject with 'id'=3

   Dynamic finders: Subject.find_by_attrName subject=Subject.find_by_id(3),當找不到數據時,返回nil

    

 

   Find all: subjects=Subject.all

    

   Find last/first

    

    

 

2八、Query methods Conditions

    where(conditions)

    

    

    

    

    

    

 

    

    

    

2九、Query methods Order, limit, and offset

    

    

    

    

    

30、Named scopes  

class Subject < ApplicationRecord
    scope :visible, lambda { where(:visible => true)}
    scope :invisible, lambda { where(:visible => false)}
    scope :sorted, lambda {order(:position => :asc)}
    scope :newest_first, lambda{order(:created_at => :desc)}
    scope :search, lambda{|query| where(["name like ?","%#{query}%"]) }
end

 

    

    

3一、Relationship types

  

 

  

  

  

  

  

3二、One to one associations

  咱們假定subject has_one page,page belongs_to subject,

  一、class with "belongs_to" has the foreign key;

  二、always define both sides of the relationship

  /app/models/subject.rb

  

  /app/models/page.rb

  

  

  

  

  

  

  

  

  

  destroy association

  

  上面命令執行後關係取消,可是page的數據依然存在在數據中

  

3三、One to many associations

  subject has_many pages,page belongs_to subject,

  

 

  /app/models/subject.rb

  

  /app/models/page.rb

  

  

  

  

  

  

  

  

  

  

 

3四、belongs to presence validation

   

  

  更改page以後

  

  

3五、Many to many associations Simple

  

  

  

  

  實例:

  step1:

  

  step2:/db/migrate/20170323055150_create_admin_users_pages_join.rb

  

  step 3:

  

  step 4:修改admin_user以及page

  

  

  測試:

  step 1:建立一個新的用戶

  

  step 2:找到一個page

  

  step 3:創建關係

  

 

3六、Many to many associations Rich

   

   實戰:

  

 

  

   /db/migrate/20170323075236_create_section_edits.rb

  

  /app/models/admin_user.rb

  

  /app/models/section.rb

  

  /app/models/section_edit.rb

  

  測試:

  找到可用的admin_user以及section

  

  生成edit

  

  單獨保存

  

  可行的作法:

  

3七、Traverse a rich association

  此節的目的在於將admin_user和section創建直接鏈接,便可經過admin_user.sections/section.admin_users得到。。。這創建在上節的基礎上

  /app/models/admin_user.rb

  

  /app/models/section.rb

  

  測試:

  

  

3八、CRUD

  

   rails generate controller Subjects index show new edit delete

   

   

3九、REST

  

   

   

40、Resourceful routes

  

4一、Resourceful URL helpers

  

  

4二、Read action Index

  

 

  /app/controllers/subjects_controller.rb

  def index
    @subjects = Subject.sorted
  end

  /app/views/subjects/index.html.erb

  

<div class="subject index">
    <h2>Subjects</h2>

    <%= link_to("Add New Subject", "#", :class => "action new") %>

    <table class="listing" summary="Subject list">
        <tr class="header">
            <th>#</th>
            <th>Subject</th>
            <th>Visible</th>
            <th>Pages</th>
            <th>Actions</th>
        </tr>
        <% @subjects.each do |subject| %>
            <tr>
                <td><%= subject.position %></td>
                <td><%= subject.name %></td>
                <td class="center"><%= subject.visible ? 'YES' : 'NO' %></td>
                <td class="center"><%= subject.pages.size%></td>
                <td class="actions">
                    <%= link_to("Show", "#", :class => "action show") %>
                    <%= link_to("Edit", "#", :class => "action edit") %>
                    <%= link_to("Delete", "#", :class => "action delete") %>
                </td>
            </tr>
        <% end %>

    </table>
</div>

 

4三、Read action Show

  修改index.rb文件

  

  修改/app/controllers/subjects_controller.rb

  

  

<%= link_to("Back to list", subjects_path, :class => "back_link") %>

<div class="subject show">
    <h2>Show Subject</h2>

    <table summary="Subject detail view">
        <tr>
            <th>Name</th>
            <td><%= @subject.name %></td>
        </tr>
        <tr>
            <th>Position</th>
            <td><%= @subject.position %></td>
        </tr>
        <tr>
            <th>Visible?</th>
            <td class="center"><%= @subject.visible ? 'YES' : 'NO' %></td>
        </tr>
        <tr>
            <th>Created</th>
            <td><%= @subject.created_at %></td>
        </tr>
        <tr>
            <th>Updated</th>
            <td><%= @subject.updated_at %></td>
        </tr>
    </table>
</div>

  

4四、Form basics

  

4五、Create action New

  

  index.rb

  

  修改/app/controllers/subjects_controller.rb

  

  /app/views/subjects/new.html.erb

<%= link_to("Back to list", subjects_path, :class => "back_link") %>

<div class="subject new">
    <h2>Create Subject</h2>

    <%= form_for(@subject)  do |f| %>
        <table summary="Subject form fields">
            <tr>
                <th>Name</th>
                <td><%= f.text_field(:name) %></td>
            </tr>
            <tr>
                <th>Position</th>
                <td><%= f.text_field(:position) %></td>
            </tr>
            <tr>
                <th>Visible</th>
                <td><%= f.text_field(:visible) %></td>
            </tr>
        </table>

        <div class="form-buttons">
            <%= f.submit("Create Subject") %>
        </div>
    <% end %>
</div>

4六、Create action Create

   

  def create
    # Instantiate a new object using form parameters
    @subject =Subject.new(params[:subject])
    # Save the Object
    if @subject.save
      #If save succeeds,redurect to the index action
      redirect_to(subjects_path)
    else
      # If save fails, redisplay the form so the user can fix problems
      render("new")
    end
  end

  

4七、Strong parameters

  

    

4八、Update actions Edit update

  

   

   

   

   

   

4九、Delete actions Delete destroy

   

    

   

    /app/views/subjects/index.html.erb

    

    /app/controllers/subjects_controller.rb

    

    /app/views/subjects/delete.html.erb

    

    

50、Flash hash

   在redirect以前個步驟操做結果提示

   

   

   

   /app/controllers/subjects_controller.rb

   

   /app/views/subjects/index.html.erb 頭部添加

   

5一、Layout

   在/app/views/layouts文件夾內新建文件admin.html.erb

   

<!DOCTYPE html>
<html>
  <head>
    <title>Simple CMS: <%= @page_title || "Admin Area" %></title>
  </head>

  <body>
      <% if !flash[:notice].blank? %>
        <div class="notice">
            <%= flash[:notice] %>
        </div>
    <% end %>
      <!-- before yield -->
    <%= yield %>
    <!-- after yield -->
  </body>
</html>

  在controller引用layout

  

  去掉html.erb文件裏面以前的notice部分的代碼,已經在layout裏面體現,並增長頁面信息

  

5二、Partial templates

  建立/app/views/subjects/_form.html.erb,將edit以及create表單部份內容複製到_form.html.erb裏面

  new喝edit頁面去掉表單已加到_form.html.erb的內容,用<%= render(:partial =>'form', :locals => { :f => f}) %>指代內容

  

  

5三、Text helpers

  TextHelper模塊提供了一組過濾,格式化和轉換字符串的方法,能夠減小視圖中的內置Ruby代碼的數量。 這些幫助方法擴展了Action View,使它們能夠在模板文件中調用。

  

5四、

5五、

5六、

5七、

5八、

5九、

60、

相關文章
相關標籤/搜索