Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails所属的有一个。需要解释一下吗_Ruby On Rails_Associations - Fatal编程技术网

Ruby on rails rails所属的有一个。需要解释一下吗

Ruby on rails rails所属的有一个。需要解释一下吗,ruby-on-rails,associations,Ruby On Rails,Associations,我有两种型号: 客户和联系人 Customers表中有列:id、:firstName、:lastName 联系人表中有列:id、:cid、:hphone、:cphone 所以如果Customers表中有数据 1 Josh McDonnel 那么Contacts表就有了相应的 5 1 947-245-2342 342-543-8585 我可以在这里使用什么关联 会有联系吗 belongs_to :customer, :foreign_key => "id", :class

我有两种型号:

客户
联系人

Customers
表中有列
:id、:firstName、:lastName

联系人
表中有列
:id、:cid、:hphone、:cphone

所以如果Customers表中有数据

1  Josh   McDonnel
那么Contacts表就有了相应的

5   1   947-245-2342 342-543-8585 
我可以在这里使用什么关联

会有联系吗

belongs_to :customer, :foreign_key => "id", :class_name => "Customer"
客户类应该有什么


另外,如果我想获得所有客户(
firstName
lastName
以及相应的
hphone
cphone
),那么简单的
查找(ubyxxx
会是什么样子记住一条规则:包含外键的表属于该外键引用的表。包含外键的表的对象“属于”不包含外键的对象

如果客户有一个联系人,并且联系人属于客户,则外键(“默认情况下为客户id”)将存在于联系人表中

您可能不想使用“id”作为外键,因为“id”是为包含联系人id的列保留的。也不需要指定类名,因为类的名称与关系的名称相同(在本例中为“客户”)

客户可能会:

has_one :contact
belongs_to :customer
联络人应:

has_one :contact
belongs_to :customer
如果你想找到某个客户的联系人,你可以打电话:

@customer.contact
反之亦然

关于XXX查找的另一个问题有点模糊。如果您想找到名为“John”的所有客户,您可以使用:

@customers_named_john = Customer.find_by_firstName("John")

但我不确定这就是你要问的。

你很接近,但你的
所属的应该是这个<代码>:外键
应该是存储对主id的引用的字段的名称:

belongs_to :customer, :foreign_key => "cid"
在您的
Customer.rb
课程中:

has_one :contact, :foreign_key => "cid"
最后,您的搜索可能如下所示:

@customers = Customer.all(:include => :contact)
然后您可以在视图中的循环中使用它:

<% @customers.each do |customer| %>
   <p>Name: <%= customer.firstName %> <%= customer.lastName %></p>
   <p>Home: <%= customer.contact.hphone %></p>
   <p>Work: <%= customer.contact.cphone %></p>
<% end %>

在他的数据库模式中,他似乎想将
客户的
id
存储在
cid
中。感谢您的精彩解释。我正在尝试执行您建议的搜索,但在我的示例中,
cid
是varchar,而
id
是整数。所以搜索不起作用并抛出错误。我可以返回并将cid更改为整数,但举例来说,我不想更改它。需要做什么工作?当然,只需运行迁移。(首先备份数据!)运行以下命令:
script/generate migration changes contacts重新启动键
并使用此代码:当然,完成这些操作后,请使用
rake db:migrate
steps@doug我有问题时,试图让所有的客户有一些电话号码。这就是我正在做的:@Omnipresent只要记住,因为它是一个
有一个
include
应该引用
:contact
单数,但是SQL条件应该引用表名,它是复数。