2015年3月18日 星期三

Ruby on Rails 資料表一對多、多對多關聯

這次要介紹的是如何在ruby on rails 中設定2個資料表之間的關聯
首先,先建立2個model
rails g model Product
rails g model Store

再來建立Product、Store的資料表結構





這次我們使用程式來建立資料表資料,不透過html的表單。在rails c底下執行Product.create(title: 'Ruby book',description:nil ,price:100) 

補充:
如何在rails c中產生圖形化的資料表內容
gemfile中新增gem 'hirb-unicode'
在終端機中執行bundle update,將hirb裝起來
接下來在rails c執行Hirb.enable,就可將Hirb功能開啟
開啟Hirb之後再執行Product.all

建立一對多關聯
在product新增一個欄位
add_column(:products,:store_id,:integer)
product.rb
belongs_to :store
store.rb
has_many :products

rails c
p1= Product.first
s1=Store.first
p1.store=s1
則p1.store.name就可取出資料
之前只是在記憶體中將資料關聯,尚未真正存進資料庫
p1.save  
s1.products

多對多關聯
先將之前的store_id刪除
remove_column(:products,:store_id)
並將之前的has_many和belongs_to
新增一個model,因為多對多關聯要拆成2個一對多
rails g model Warehouse
在新增的create_warehouse下輸入
      t.belongs_to :product
      t.belongs_to :store
前面2行與底下2行程式意義相同
      t.integer :product_id
      t.integer :store_id
在終端機直行rake db:migrate,新增Warehouse資料表

在Warehouse的model
    belongs_to :product
    belongs_to :store
在Products的model
    has_many :warehouses
    has_many :stores, :through => :warehouses
在Store的model
    has_many :warehouses
    has_many :products, :through => :warehouses

在rails c
先將p1~p3,s1~s2先取出,並將p1,p2存入s1
s1.products=[p1,p2]
s2.products=[p2,p3]
接下來執行
s1.products或p2.stores都能看見結果
但離開rails c前要記得把s1,s2存檔

補充:
若是不曉得某一個英文單字的複數形態是甚麼,不需要翻字典,直接在rails c之下執行 'student'.pluralize,' '單引號之內的就是要查詢的單字