我有一個HABTM關係,並希望以確定是否在一個方向上的兒童已被添加或刪除。我試圖使用回調,但發現我沒有對孩子進行更改的記錄。有沒有像course.students.changed?
使用:
- 的Rails 3.0.3
- 紅寶石1.9.2p0
表:
學生 - ID,名字,姓氏
門課程 - 編號,名稱,位置
courses_students - COURSE_ID,student_id數據
型號:
class Course
# Callbacks
before_save :student_maintenance
# Relationships
has_and_belongs_to_many :students
protected
def student_maintenance
# I want to do something like
students.changed?
students.changes.each do |student|
if marked_for_deletion
# do something
elsif marked_for_addition
# do something else
end
end
end
end
end
class Student
# Relationships
has_and_belongs_to_many :courses
end
這是否意味着我必須改變關係? I.e課程has_many:courses_students,Course_Student belongs_to:課程belongs_to:學生,學生has_many:courses_students。我是否正確複數? – Becky
您可能會將「has_and_belongs_to_many」關係更改爲「has_many through」(http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association)。 「學生has_many:課程:通過=>:courses_students」和「課程has_many:students,:through =>:courses_students」這樣的句子可能會更好一些,但可能會有更具描述性的連接模型名稱。然後,您的加入模式「班級課程學生」將包含「belongs_to:student」和「belongs_to:course」以及您的回調。你懂我的意思嗎? – polarblau
所以把has_many的habtm通過。我想我明白了。我會試試看,如果它適合我,請將其標記爲正確。 – Becky