Rails一对多关系方法

时间:2011-12-01 17:12:00

标签: ruby-on-rails activerecord

class Contact < ActiveRecord::Base
    has_many :records
end

class Volunteering::Record < ActiveRecord::Base
    belongs_to :contact
end

rails console
    > Contact.last.records #NameError: uninitialized constant Contact::Record

如果我将班级联系人改为has_many:volunteering_records,那么我得到:

  

Contact.last.volunteering_records#NameError:uninitialized constant Contact :: VolunteeringRecord

我的志愿者::记录课有外键:

  

Volunteering :: Record.column_names.include?('contact_id')#true

有什么建议吗?

更新: 我想到了。由于它位于不同的命名空间中,因此需要指定完整的类名:

:has_many records, :class_name => "Volunteering::Record"

1 个答案:

答案 0 :(得分:0)

更改志愿者::记录到只记录,你的例子应该工作得很好。如果您正在寻找中间表,您想使用:has_many,:through。