我現在正在軌道上做紅寶石項目。我創建了一個名爲product的實體,我想設置與其他實體命名的category的多對多關係。在rubyonrails中通過腳手架設置引用表格
script/generate scaffold product prd_name:string category:references
通過這樣做的代碼只有一對一的映射是可能的。我如何設置多對多沒有硬編碼?
我現在正在軌道上做紅寶石項目。我創建了一個名爲product的實體,我想設置與其他實體命名的category的多對多關係。在rubyonrails中通過腳手架設置引用表格
script/generate scaffold product prd_name:string category:references
通過這樣做的代碼只有一對一的映射是可能的。我如何設置多對多沒有硬編碼?
我們不能通過腳手架來做到這一點。我們必須編輯班級的模型來設置多對多的關係。
您不應該期望能夠通過腳手架單獨生成您的應用程序。這只是爲了提供一個入門示例。
軌道中最靈活的多對多關係稱爲has many through。這需要一個連接表,在這種情況下通常被稱爲「分類」。它需要一個product_id
列,聲明爲belongs to :product
和category_id
列,聲明爲belongs_to :category
。這三個模型(包括聯接模型)將因此宣佈:
# Table name: products
# Columns:
# name:string
class Product < ActiveRecord::Base
has_many :categorisations
has_many :categories, through: :categorisations
end
# Table name: categories
# Columns:
# name:string
class Category < ActiveRecord::Base
has_many :categorisations
has_many :products, through: :categorisations
end
# Table name: categorisations
# Columns:
# product_id:integer
# category_id:integer
class Categorisation < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
請注意,我命名列name
而非prd_name
,因爲這是人類可讀的,避免了表名的冗餘重複。使用導軌時強烈建議使用此功能。
該機型可以這樣產生:
rails generate model product name
rails generate model category name
rails generate model categorisation product:references category:references
至於產生的腳手架,你可以在頭兩個命令與scaffold
取代model
。雖然如此,除了作爲一種看待學習的例子的方式之外,我不推薦它。
有可能產生與參考模型,像這樣
$ rails generate model Comment commenter:string body:text post:references
命令見http://guides.rubyonrails.org/getting_started.html#generating-a-model
它現在可以生成具有引用支架,像這樣
$ rails generate scaffold Comment commenter:string body:text post:references
這是不正確的(再見),參見瑞卡斯特羅的回答。 – slhck