0

我有两个模型,会议和与会者,它们共享一个 habtm 关系。我还有一个会议可以属于的用户模型(作为会议组织者)。

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声明上添加 aUser并且可以删除该:association_foreign_key选项,因为它是默认设置。实际上,您也可能会失去该:class_name选项,因为这也是默认设置。所以:

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