所以,如果我有隻是它的ID的MANY_TO_MANY表,我想另一個模型中引用它,我將如何做呢?Ruby on Rails的 - 引用MANY_TO_MANY關係
因此,在這個名爲評級的模型中,我想說它與該關聯中的這兩件事有關,在本例中爲課程和教科書。所以評分是由教科書和課程定義的。我是否應該將兩個ID屬性添加到鏈接到兩者的評分?我應該向many_to_many添加一個ID,然後在Rating表中添加一個ID屬性?或者還有什麼我可以做的嗎?
UPDATE:
因此,這裏是我的ERD至今。你可以忽略與學生和教授的事情。 在右側,我根據@RichPeck製作的表格。我很困惑如何創建條目。比方說,我創建一個課程。
course = Course.new(params)
我那麼做是爲了一本教科書。
textbook = course.textbooks.build(params)
現在,當我做course.textbooks
,它會列出我剛纔提出的教科書,但是當我做textbook.courses
我得到一個空列表。另外,保存它們並退出shell然後重新打開後,這兩個命令都會返回空列表。現在這是因爲連接表CourseTextboks是空的。爲什麼rails沒有添加入口呢?我需要做一些特別的事嗎?
以下是相關文件:
CreateCourseTextbooksMigration
class CreateCourseTextbooks < ActiveRecord::Migration
def change
create_table :course_textbooks do |t|
t.references :course, index: true
t.references :textbook, index: true
t.timestamps
end
end
end
CreateTextbookMigration
class CreateTextbooks < ActiveRecord::Migration
def change
create_table :textbooks do |t|
t.string :title
t.string :authors
t.string :edition
t.float :price
t.string :isbn
t.text :description
t.string :image_url
t.date :published
t.timestamps
end
end
end
CreateCourseMigration
class CreateCourses < ActiveRecord::Migration
def change
create_table :courses do |t|
t.string :title
t.string :letters
t.integer :number
t.timestamps
end
end
end
而MOD ELS:
場
class Course < ActiveRecord::Base
has_many :student_courses
has_many :students, through: :student_courses
has_many :professor_courses
has_many :professors, through: :professor_courses
has_many :textbook_courses
has_many :textbooks, through: :textbook_courses
validates_presence_of :title, :letters, :number
end
教材
class Textbook < ActiveRecord::Base
has_many :textbook_courses
has_many :courses, through: :textbook_courses
end
CourseTextbook
class CourseTextbook < ActiveRecord::Base
belongs_to :course
belongs_to :textbook
has_many :rating_course_textbooks, :class_name => "RatingCourseTextbook"
has_many :ratings, :through => :rating_course_textbooks
validates_presence_of :course
end
你能幫助我嗎,夥計們?
UPDATE2:
我想通了搜索和比較注重創建對象時,生成的SQL大約一個半小時後。所以當你做一個course.build
它只是返回的對象,並以某種方式鏈接它,而不是通過連接表。我發現,你必須拯救而不是課程的新來的教授,或者只是使用創建。
這是發生了什麼事
>>> course = Course.create(params)
# INSERT into courses table
>>> professor = course.build(params)
>>> professor.save
# INSERT into professors table
>>> course.professors
# [Professor {id:1, blah}]
>>> professor.courses
# []
這是現在
>>> course = Course.create(params)
# INSERT into courses table
>>> professor = course.build(params)
>>> course.save
# INSERT into professors table
# INSERT into professor_courses table
>>> course.professors
# [Professor {id:1, blah}]
>>> professor.courses
# [Course {id:1, blah}]
YAY是什麼在起作用!現在,只是爲了看看它所有我的其他機型的作品,像RatingsCourseTextbooks
UPDATE3 所以亂搞一小會兒後,我發現,我正在它太複雜了。評分只能有一個CourseTextbook,所以我不需要另一個連接表。我只是添加了CourseTextbook ID來評級。
感謝您的支持
有更好的解釋。 –
這是一個多態關係的非常好的解釋,我很欣賞那是因爲它是有價值的知識,但我相信你不是誤解就是我溝通不佳,但是我想要的是爲教科書所在的課程設置一本教科書的評分。我希望爲課本和課程評分。我不評價課程。 – adamk33n3r
你可以使用'has_many:through'來表達你發佈的內容 - 讓我爲你寫! –