2012-09-11 106 views
0

我只是想不通,为什么这个协会是不工作...我敢肯定,这是好的,但是找不到错字导轨的has_many:渡过难关

class Lesson < ActiveRecord::Base 
    has_many :lessons_units, :foreign_key => "lesson_id", 
          :dependent => :destroy 
    has_many :units, :through => :lessons_units 
end 

class Unit < ActiveRecord::Base 
    has_many :lessons_units, :foreign_key => "unit_id", 
          :dependent => :destroy 
    has_many :lessons, :through => :lessons_units 
end 


class LessonsUnits < ActiveRecord::Base 
    attr_accessible :lesson_id, :unit_id 

    belongs_to :unit 
    belongs_to :lesson 

    validates :unit_id, :presence => true 
    validates :lesson_id, :presence => true 
end 

然后在控制台

1.9.3p194 :001 > Unit.lessons.build 
NoMethodError: undefined method `lessons' for #<Class:0x007fe733c29f30> 
from /Users/robert/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/dynamic_matchers.rb:50:in `method_missing' 

以及App

def create 
    @unit = Unit.find(params[:unit_id]) 
    @lesson = @unit.lessons.build(params[:lesson]) 

结果:

uninitialized constant Unit::LessonsUnit 
+0

你应该考虑使用['has_and_belongs_to_many'协会(http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association) 。它不会解决这个问题,但它会简化你的代码。 – georgebrock

+0

我相信has_and_belongs_to_many从3.1开始折旧,所以我尽可能避免它。我同意它的清洁。 – Robert

+0

我的理解是,在连接表中存储额外的数据(即超过两个ID)已被弃用,但关联类型不是。 [Rails 3.1发行说明](http://guides.rubyonrails.org/3_1_release_notes.html)中没有关于弃用的内容。 – georgebrock

回答

0
LessonsUnits - 

class LessonsUnits < ActiveRecord::Base 

应为单数:

class LessonsUnit < ActiveRecord::Base 
0

终于搞明白了。这是因为我的链接模型以's'结尾 - 导轨将它转化为单数。注意到它,因为错误显示模型没有's' - Unit :: LessonsUnit而不是Unit :: LessonsUnits

将关系编辑为:lessons_unitss修复它...我要通过并重命名模型不是复数。

+0

未来它将有助于您在上下文中解释您的问题。在这种情况下,试图将问题从控制器中抽象出来,导致了另一个似乎是问题核心的无关问题。很高兴你把它整理出来。 – deefour

+0

感谢您提供答案的时间。对此,我真的非常感激。我在控制器上花了一个小时,然后再回到控制台,我想我在尝试简化时需要更小心。 :) – Robert

+0

你应该接受你自己的答案;你自己解决了这个问题:) – deefour