20140608 learn by Ruby on Rails Tutorial

来源:互联网 发布:mac如何设置两个桌面 编辑:程序博客网 时间:2024/05/16 06:11

创建新项目: rails new

配置git:

本地git:

1. git init

2. git add . : "."表示当前directory

3. git commit


和github remote repository建立链接:

1. git remote add origin https://github.com/<username>/first_app.git

2. git push -u origin master

Interact with remote repository:

git push origin master: "origin master"可略


Git command:

git checkout -b: checkout到新branch

git checkout: switch branch

git mv - rename

git commit -a : commit all modifications, 如果有新加的文件的话还是要先add

git branch:

利用branch开发的流程:先创建并checkout到新branch,修改完commit后,checkout回master,再merge

git branch -d: 删除已被merge的branch

git branch -D:强制删除

HTTP小知识

GET: get a page

POST: submit a form (POST requests are typically used forcreating things)

神秘的Gemfile...

~>: means only install updated gems representing minor point releases

ERb

<% ... %>: executes the code inside

<%= ... %>: executes it and inserts the result into the template

provide(:symbol, object): 为symbol map 一个object

Rails helper

在application_helper中放自定义的辅助函数

By default, all the helpers are available in the views but not in the controllers.要在controllers中用的话要在Application controller中include

Rails partials

一般命名以"_"开头

putting partials that are literally on every page (as part of the site layout) in thelayouts directory.

use the shared folder for utility partials that are useful on multiple views

用render来调用 - e.g., render 'layouts/header' ,即look for a file calledapp/views/layouts/_header.html.erb

rails method

.blank? - 检查string是否只包含whitespace

form_for - takes in an Active Record object and constructs a form using the object’s attributes

pluralize(num, 'text')

link_to(text, url): create links, the first argument is the link text, while the second is the URL.

image_tag(path, optianal hash)

Sass

 & - reference the parent element

vairable以$开头

Controller

创建controller和actions: rails generate controller ControllerName action (一般controller的名字是复数)

撤销generate: rails destroy controller <ControllerName> <ActionName>

手工新建action的步骤

route -> controller -> view

在view中的变量实在controller中的相应method里定义的

Routes

产生path:match '/help',to:'static_pages#help',via:'get' (creates named routes: help_path, help_url)

而对于root:root 'static_pages#home'

看所有routes: rake routes


RSpec tests

生成integration test: rails generate integration_test <test_name> --no-test-framework

运行test, rake spec

测试model / db

$ bundle exec rake db:migrate

$ bundle exec rake test:prepare

$ bundle exec rspec spec/models/user_spec.rb

whenever an object responds to a boolean method foo?, there is a corresponding test method calledbe_foo

Models

Active Record: the default library for interacting with the database

创建models:

先generate model:rails generate model User name:string email:string (一般model的名字是单数,这一步creates a migration file)

然后migrate db:bundle exec rake db:migrate

migration: Migrations provide a way to alter the structure of the database incrementally, so that our data model can adapt to changing requirements.

存入db

obj = Model.new ; obj.save 

或  Model.create

从db中删掉:obj.destroy

update: 1)直接obj.attr=xxxx,记得save

2)update_attributes(hash),update save一步到位 (或单数形式:user.update_attribute(:name,"The Dude")

.update_attribute - this method allows us to update a single attribute while bypassing the validations

.reload - reloads the object based on the database information

find objects: Model.find(id) / Model.find_by(key: value)

.first / .all

.count

.dup - creates a duplicate user with the same attributes

before_save - 一个callback,把存入db前要运行的代码放这里

Validation

语法(presence validation):validates(:attr, presence:true)

obj.valid? - returns false when the object fails one or more validations

check error:user.errors.full_messages

length validation- length: { maximun: 50 }

format validation -

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

validates :email,presence:true,format:{with:VALID_EMAIL_REGEX}

uniqueness validation -

在model的rb文件中写入uniqueness:true( case-sensitive! )  /  uniqueness:{case_sensitive:false}

在db level控制uniqueness - 先generate migration,在生成文件的change方法中写入add_index:users, :email,unique:true (:users是表名),再运行rake migrate

add attribue to model

rails g migration add_password_digest_to_users  attr:type (by convention, migration name should end with_to_users)

在生成的migrate文件的change method中写入 add_column :users, :remember_token, :string 之类的

password处理

在model中添加password_digest attrubute

has_secure_password

.authenticate(password): If the given password matches the user’s password, it should return the user; otherwise, it should returnfalse.

REST

REST means that most application components (such as users and microposts) are modeled as resources that can be created, read, updated, and deleted (index,show, new, edit, create, update and destroy)

在routes里加一行( resources :users) automatically ensures that our Rails application responds to the RESTful URLs

read (show)

when Rails’ REST features are activated, GET requests are automatically handled by theshow action.


在views里加一个show.html.erb file

在controller中加show method,@user=User.find(params[:id])

create

POST request is handled by create action

strong parameters - 直接用传入的params新建obj很危险,要先处理一下

params.require(:user).permit(:name, :email, :password, :password_confirmation)

View

flash - 在layout/application里加一段flash

persist for one request (redirect 算request,render不算)

flash.now - specifically designed for displaying flash messages on rendered pages,its contents disappear as soon as there is an additional request.

Session

save user id - session[:remember_token]=user.id

retrieve user - User.find(session[:remember_token])

cookies - rails utility

cookies.permanent[:remember_token]= remember_token

cookies.destroy












0 0
原创粉丝点击