has_many& belongs_to不在rails中工作

时间:2011-02-17 11:56:13

标签: ruby-on-rails has-many belongs-to

我创建了两个模型1)联系2)我的Rails应用程序中的客户,现在我想加入这些模型的两个表。表格是联系人和客户分别。我使用以下代码:

1)contact.rb:

class Contact < ActiveRecord::Base
  unloadable
  has_many :customers
end

2)customer.rb

class Customer < ActiveRecord::Base
  belongs_to :contact, :foreign_key => :contact_id`
end

3)customers_controller.rb

def new
  @customer = Customer.new
  @customer = Customer.find(:all,:include => :contact_id)
end

这里我试图将联系人表的主键访问到customer表中,但是它反复给出了这个错误“找不到名为'contact_id'的联想;也许你拼错了吗?”任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

当您使用include时,您应该传递关联名称(在您的情况下为“contact”)而不是外键。

但是,您的描述并未明确说明这是您要执行的操作,因此如果您能澄清您的问题,我会在错误时更新此答案

答案 1 :(得分:0)

如果我清楚地了解您不需要在联系模式中使客户多元化:

class Contact < ActiveRecord::Base
  unloadable
  has_many :customers
end

并且您不需要指定包含外键的列的名称

(对不起我的英文)