2010-11-23 101 views
0

我有3個模型類別,問題和測驗以及5個表格類別,問題,測驗,category_quizzes和questions_quizzes。需要RoR模型關係建議

測驗有很多問題,可能屬於零個或多個類別。另外一個可能的問題屬於多個測驗

一些機構可以建議應該如何模型

表架構之間的關係如下

CREATE TABLE categories (
    id int(11) unsigned NOT NULL auto_increment, 
    title varchar(255) NOT NULL, 
    PRIMARY KEY (id), 
); 

CREATE TABLE category_quizzes (
    id int(11) unsigned NOT NULL auto_increment, 
    category_id int(11) unsigned NOT NULL, 
    quiz_id int(11) unsigned NOT NULL, 
    PRIMARY KEY (id), 
    KEY category_id (category_id,quiz_id), 
    KEY quiz_id (quiz_id) 
); 

CREATE TABLE questions (
    id int(11) unsigned NOT NULL auto_increment, 
    question varchar(255) NOT NULL, 
    answer varchar(255) NOT NULL, 
    PRIMARY KEY (id), 
); 

CREATE TABLE questions_quizzes (
    id int(11) unsigned NOT NULL auto_increment, 
    quiz_id int(11) unsigned NOT NULL, 
    question_id int(11) unsigned NOT NULL, 
    PRIMARY KEY (id), 
    KEY quiz_id (quiz_id,question_id), 
    KEY question_id (question_id) 
); 

CREATE TABLE quizzes (
    id int(11) unsigned NOT NULL auto_increment, 
    title varchar(255) NOT NULL, 
    PRIMARY KEY (id), 
); 

我目前的模型類

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :quiz 
end 

class Question < ActiveRecord::Base 
    has_and_belongs_to_many :quiz 
end 

class Quiz < ActiveRecord::Base 
    has_many :questions 
    has_and_belongs_to_many :categories 
end 

回答

0

的表category_quizzes的遷移不正確。它應該是categories_quizzes,都是複數形式。

然後,你可以指定這樣的關聯:

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :quizzes 
end 

class Question < ActiveRecord::Base 
    has_and_belongs_to_many :quizzes 
end 

class Quiz < ActiveRecord::Base 
    has_and_belongs_to_many :questions 
    has_and_belongs_to_many :categories 
end 

編輯:根據您的評論

+0

其實一個問題可能會出現在許多測驗 – 2010-11-23 09:02:28