[英]Use belongs_to association in Rails 4
I am reading the docs, and they say about belongs_to: 我正在阅读文档,并且他们说到belongs_to:
Specifies a one-to-one association with another class. 指定与另一个类的一对一关联。 This method should only be used if this class contains the foreign key. 仅当此类包含外键时,才应使用此方法。
I have 3 models: 我有3种型号:
Info
Customer
Seller
I need that every instance of Customer or Seller can be linked to one row in the infos table. 我需要将Customer或Seller的每个实例都可以链接到infos表中的一行。
So I think I just need to put the foreing_key info_id in the 2 models, and specify a belongs_to :info
association. 所以我想我只需要将foreing_key info_id放在两个模型中,并指定一个belongs_to :info
关联即可。
But when I do this: 但是当我这样做时:
@customer.info
It gives me error because is trying to execute this query: 它给我错误,因为试图执行此查询:
SELECT `auth_infos`.* FROM `auth_infos` WHERE `auth_infos`.`customer_id` = 1 LIMIT 1
But for what I need and what I underatand from the docs it should execute this one: 但是对于我所需要的以及我对文档的了解,它应该执行以下操作:
SELECT `auth_infos`.* FROM `auth_infos` WHERE `auth_infos`.`id` = 1 LIMIT 1
What am I missing? 我想念什么?
You should do it like 你应该这样做
info model 信息模型
has_one :customer
has_one :seller
customer model 客户模型
belongs_to :info
seller model 卖方模型
belongs_to :info
model having belongs_to always contain foreign key . 拥有属类的模型始终包含外键 。 So customer and seller table will have info_id foreign keys. 因此,客户和卖方表将具有info_id外键。
info_id
After that you can get both customer and seller linked with info and vice versa. 之后,您可以使客户和卖方都与信息链接,反之亦然。
@customer.info
@info.customer
@seller.info
@info.seller
The docs express the relationship incorrectly. 该文档表达了错误的关系。 "Belongs_to" doesn't state anything about the cardinality of the other model, only that whatever the other model is, it can only have zero or one of whatever "belongs_to" it. “ Belongs_to”没有声明关于另一个模型的基数的任何信息,只是说无论其他模型是什么,它只能有零个或任何一个“ belongs_to”之一。
If ... 如果...
Price belongs_to Book
Book has_one Price
... then a book can have zero or one prices, and a price can only belong to one book. ...那么一本书可以有零个或一个价格,而一个价格只能属于一本书。
If ... 如果...
Price belongs_to Book
Book has_many Price
... then a book can have zero or many prices, and again a price can only belong to one book. ...那么一本书可以有零个或多个价格,而且价格只能属于一本书。
If a Customer or a Seller can optionally have at most one Info, and onfo can have either zero or one Customer or Seller, then make Info polymorphic and let Customer and Seller "has_one informable" (or similar). 如果客户或卖方可以选择最多包含一个信息,并且onfo可以具有零个或一个或多个客户或卖方,则应使信息多态,并让客户和卖方“拥有一个可通知的信息”(或类似信息)。 Then Info "belongs_to informable" 然后信息“属于”
You can use polymorhic association. 您可以使用多态关联。 make Info model polymorhic. 使信息模型多面。
info.rb info.rb
class Info < ActiveRecord::Base
belongs_to :informable, polymorphic: true
end
customer.rb customer.rb
class Customer < ActiveRecord::Base
has_one :info, as: :informable
end
seller.rb seller.rb
class Seller < ActiveRecord::Base
has_one :info, as: :informable
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.