0

我只是无法弄清楚为什么这个关联不起作用......我很确定这没关系,但找不到错字

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'

并在应用程序中

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

结果:

uninitialized constant Unit::LessonsUnit
4

2 回答 2

0

终于想通了。这是因为我的链接模型以“s”结尾-rails 将其转换为单数。注意到它是因为错误显示模型没有's' - Unit::LessonsUnit 而不是 Unit::LessonsUnits

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

于 2012-09-11T21:34:27.943 回答
0
LessonsUnits - 

class LessonsUnits < ActiveRecord::Base

应该是单数:

class LessonsUnit < ActiveRecord::Base
于 2012-09-11T21:37:48.757 回答