有_许多& belongs_to 不在 Rails 中工作

发布于 2024-10-18 00:43:41 字数 610 浏览 6 评论 0原文

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

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

这里我试图将联系人表的主键访问到客户表中,但它反复给出此错误“名为“contact_id”的关联是没找到;也许你拼错了?”有人可以帮我解决这个问题吗?

I have created two models 1) Contact 2) Customer in my Rails application, now I want to join the two tables of these models. Tables are contacts & customers respectively. I am using following code:

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

Here I am trying to access the primary key of contact table into customer table but it repeatedly gives this error "Association named 'contact_id' was not found; perhaps you misspelled it?" Can any one help me on this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稚气少女 2024-10-25 00:43:41

当您使用 include 时,您应该传入关联名称(在您的例子中为“contact”)而不是外键。

但是,您的描述并没有明确表明这就是您想要做的,所以如果您能澄清您的问题,如果它是错误的,我会更新这个答案

When you use include, you should pass in the association name (in your case "contact") rather than the foreign key.

However, your description doesn't make clear that this is what you want to do, so if you can clarify your question I'll update this answer if it's wrong

暖伴 2024-10-25 00:43:41

如果我清楚地理解您不需要在联系人模型中将客户复数:

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

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

(对不起我的英语)

If I clearly understand you don't need to pluralize customer in the contact model :

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

And you don't need to specified the name of the column who contain the foreign key

(sorry for my english)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文