rails habtm association实现给出问题

时间:2012-05-23 14:47:14

标签: ruby-on-rails

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

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)
=>  

1 个答案:

答案 0 :(得分: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声明中添加User,并可以删除:association_foreign_key选项,因为它是默认设置。实际上你也可能失去:class_name选项,因为这也是默认选项。所以:

has_and_belongs_to_many :meetings, 
    :foreign_key => "attendee_id"