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」で終わっているためです。レールはそれを単数形に変換していました。Unit::LessonsUnits の代わりに Unit::LessonsUnit - Unit::LessonsUnit

:lessons_unitss への関係を編集すると修正されます... モデルの名前を複数形にならないように変更します。

于 2012-09-11T21:34:27.943 に答える
0
LessonsUnits - 

class LessonsUnits < ActiveRecord::Base

単数でなければなりません:

class LessonsUnit < ActiveRecord::Base
于 2012-09-11T21:37:48.757 に答える