0

私は、habtm 関係を共有する 2 つのモデル、会議と出席者を持っています。また、会議が属することができる User モデルもあります (会議の主催者として)。

class Meeting < ActiveRecord::Base
  belongs_to :organizer, :class_name => User, :foreign_key => "organizer_id"
  has_and_belongs_to_many :attendees, :class_name => User, :association_foreign_key => "attendee_id"
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :meetings, :class_name => Meeting, :association_foreign_key => "meeting_id"
end

そして、私は関係テーブルを持っています..

create_table "attendees_meetings", :id => false, :force => true do |t|
  t.integer "attendee_id"
  t.integer "meeting_id"
end

新しい会議を作成し、出席者を meeting.attendees として参照すると、エラーが発生します。オーガナイザーの場合も同じで、meeting.organizer はエラーをスローします。関係を適切に設定していませんか?

m = Meeting.create(:subject => "Test", :location => "Neverland", :body => "A test", :organizer_id => 8)
m.organizer
NoMethodError: undefined method `match' for #<Class:0x00000103d8cf08>

出席者も同じです (ただし、現時点では何も定義していませんが、エラーをスローするべきではありません)。

1.9.2-p318 :014 > m.attendees
(Object doesn't support #inspect)
=>  
4

1 に答える 1

0

class_nameオプションhas_and_belongs_to_manyは、クラスの名前である文字列である必要があります。クラス オブジェクト自体を渡しました。たとえば、

has_and_belongs_to_many :attendees, 
    :class_name => "User", 
    :association_foreign_key => "attendee_id"

モデル:foreign_key => 'attendee_id'has_and_belongs_to_many宣言にa を追加する必要があり、デフォルトであるためオプションを削除できると思います。実際には、オプションもデフォルトであるため、オプションを失う可能性があります。そう:User:association_foreign_key:class_name

has_and_belongs_to_many :meetings, 
    :foreign_key => "attendee_id"
于 2012-05-23T14:59:01.547 に答える