2012-09-13 44 views
0

我在這裏有兩種模式,即課程和studyunits,其中studyunit包含課程內容。has_and_belongs_to_many無法從關係兩側訪問

這裏有兩種型號:

class Studyunit < ActiveRecord::Base 
    attr_accessible :name 
    has_and_belongs_to_many :courses 

class Course < ActiveRecord::Base 
    attr_accessible :name 
    has_and_belongs_to_many :studyunits 

的問題是,添加studyunits到課程似乎更新的過程。 studyunits屬性,但不studyunit.courses。 rspec編號摘錄:

before(:each) do 
    course.studyunits << studyunit 
    Studyunit.connection.clear_query_cache 
end 

it "should be associated with a course" do 
    course.studyunits.first.should_not eql(nil) 
    studyunit.courses.first.should_not eql(nil) 
end 

第一個條件通過,第二個條件失敗。如何解決這個問題?我需要在我的代碼中訪問雙方。我試圖按照this thread清除查詢緩存,但它沒有解決問題。

回答

0

你確定這不僅僅是緩存嗎?我懷疑它的確如此。試試這個代碼,而不是:

it "should be associated with a course" do 
    course.studyunits(true).first.should_not eql(nil) 
    studyunit.courses(true).first.should_not eql(nil) 
end 
+0

好吧,那就修好了。該參數(我認爲)關閉緩存?我只是在另一個麻煩的地方用我的代碼調用它,它完美地工作。 – HaskellMan

+0

它只是告訴activerecord不使用關係的緩存版本。如果沒有提供值,它將使用緩存版本(如果可用)。 – weexpectedTHIS