私は、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)
=>