1/新建項目
$rails new depot -d mysql
2/進入文件夾目錄
$cd depot
3/x修改項目文件
Gemfile----source 'https://ruby.taobao.org'(國內鏡像源)/gem 'mysql2','0.3.11'(指定數據庫)
config/routes.rb----match ':controller(/:action(/:id))(.:format)'(去掉註釋)
config/databases.yml----password: 'xxxxx'(修改密碼,注意英文空格,純數字需要外加‘’單引號)
4/重新加載修改文件
$bundle install
6/啓動數據庫
$mysql -u root -p #進入數據庫
mysql> show databases; #顯示當前數據庫,注意;分號爲語句結束符
mysql>use mysql; #使用自己的數據庫
mysql>ctrl+c(退出)
7/創建數據庫
$rake db:create #創建數據庫
8/創建模型
$rails g model Product #創建模型,模型名字大寫字母開頭,對應的數據庫表名爲products(複數),每創建一個模型,db/migrate下會生成對應的遷移文件
9/添加元素字段
$rails g model Product title:string description:string price:integer(注意單詞拼寫)
$rails g migration add_ID_to_products #後期添加元素字段,文件名意在說明文件作用
10/用戶自定義文件
1)views下新建products文件夾,存放用戶代碼;
2)app/controllers下新建products_controller.rb,用於方法定義,即控制器(注意命名不能爲複數)
3)app/views/products下新建index.html.erb/new.html.erb/edit.html.erb等,用於編寫頁面顯示代碼
11/加載程序更改內容
$rake db:migrate
12/啓動服務器
$rails s
$rails c #打開控制器
13/效果查看
在瀏覽器的新頁面輸入地址127.0.0.1:3000/products/index
多個數據庫表的鏈接查詢:
1)#在teachers_controller.rb文件下進行index的方法定義
def index
@teachers = Teacher.where(:xueyuan_ID => params[:id])
end
2)#在views/teachers/iindex.html.erb文件下進行id寫入
<td>
<a href="/teachers/delete?id=<%=teacher.id%>">delete</a>
<a href="/teachers/edit?id=<%=teacher.id%>">update</a>
<a href="/students/index?id=<%=teacher.t_ID%>">students
</td>
!!!錯誤解決:
#index----Routing error:注意各文件命名的細節,如單詞拼寫/單複數等,products_controller(單數)
#new----name error:注意實例變量的使用,product/products/@product的區別
#update----ActiveRecord::RecordNotFound...:注意循環模塊的使用@products each do| product |
#create----ActiveRecord::StatementInvalid...:看錯誤提示的位置,檢查語法錯誤
1