简体   繁体   English

has_many和belongs_to在rails中不起作用

[英]has_many & belongs_to is not working in rails

I have created two models 1) Contact 2) Customer in my Rails application, now I want to join the two tables of these models. 我已经在Rails应用程序中创建了两个模型1)联系2)客户,现在我想加入这些模型的两个表。 Tables are contacts & customers respectively. 表分别是联系人和客户。 I am using following code: 我正在使用以下代码:

1) contact.rb: 1)contact.rb:

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

2) customer.rb 2)customer.rb

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

3) customers_controller.rb 3)customer_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?" 在这里,我尝试将联系人表的主键访问到客户表中,但是它反复出现此错误“找不到名为'contact_id'的关联;也许您拼写错误了吗?” Can any one help me on this? 谁可以帮我这个事?

When you use include , you should pass in the association name (in your case " contact ") rather than the foreign key. 使用include ,您应该传入关联名称(在您的情况下为“ contact ”),而不是外键。

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 但是,您的描述并不清楚您要执行的操作,因此,如果您可以澄清问题,我将在错误的情况下更新此答案

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) (对不起我的英语不好)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM