has_and_belongs_to_many无法从关系的两边访问

时间:2012-09-13 05:56:27

标签: ruby-on-rails activerecord rspec

我在这里有两个模型,课程和学习单元,其中一个学习单元有课程内容。

以下是两种模式:

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属性,但不是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清除查询缓存,但它没有解决问题。

1 个答案:

答案 0 :(得分: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