【问题标题】:has_and_belongs_to_many not accessible from both sides of the relationhas_and_belongs_to_many 无法从关系的双方访问
【发布时间】:2012-09-13 05:56:27
【问题描述】:

我这里有两个模型,课程和学习单元,学习单元包含课程的内容。

这是两个模型:

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

【问题讨论】:

    标签: ruby-on-rails activerecord rspec


    【解决方案1】:

    您确定这不仅仅与缓存有关吗?我怀疑确实如此。试试这个代码:

    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
    

    【讨论】:

    • 好的,解决了。该参数(我假设)关闭缓存?我刚刚在另一个问题点的代码中调用了它,它运行良好。
    • 它只是告诉 activerecord 不要使用关系的缓存版本。如果未提供任何值,它将使用缓存版本(如果可用)。
    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2020-12-13
    • 2017-02-17
    相关资源
    最近更新 更多