Rails has_one关联混乱 [英] Rails has_one association confusion

查看:87
本文介绍了Rails has_one关联混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Rails还是很陌生,我想创建一个具有一个地址的Person模型和一个具有一个地址和一个Person的公司模型.

I am very new to Rails and I want to create a Person model that has one Address and a Company Model that has one Address and one Person.

这是我到目前为止所做的

Here is what I've done so far

$ rails generate model Address street:string suburb:string 

$ rails g scaffold Person name:string address:references

$ rails g scaffold Company name:string person:references address:references


    class Address < ActiveRecord::Base
      belongs_to :person
      belongs_to :company
    end

    class Person < ActiveRecord::Base
      has_one :address
    end

    class Company < ActiveRecord::Base
      has_one :person
      has_one :address
    end

很明显,我缺少了一些东西.地址是否需要多态关联?

Obviously I am missing something. Does Address need a polymorphic association?

我很迷茫,所以任何指导都将不胜感激.

I am pretty lost, so any guidance would be appreciated.

欢呼

推荐答案

您丢失了外键和/或将它们放在不正确的位置.请记住,子代"模型中需要外键.这就是所拥有的模型. Person has_one地址也是如此,该地址是拥有的,并且应包含引用该Person的外键.

You are missing you foreign keys and/or have them in the incorrect place. Remember that a foreign key is needed in the 'child' model. That is the model that is possesed. So is a Person has_one address, the address is possessed, and should contain a foreign key that references the Person.

外键是数据库中的列,或者是模型中的属性,其中包含关联的拥有者模型的ID.例如,在数据库中belongs_to一个Person的地址模型将如下所示:

A foreign key is a column in the database, or an attribute in the model, that holds the id of the associated possessor model. For example an Address model that belongs_to a Person will look like this in the database:

Address -->   | address_id  | person_id | street | suburb |

如果它属于一个人和一个公司,它应该看起来像这样.

If it belongs to a Person and a Company it should look like this.

Address --> | address_id  | person_id | company_id | street | suburb |

您应该像上面那样生成上述脚手架代码,而不是上面的代码:

Instead of the above you should generate your scaffold code like so:

$ rails generate model Address street:string suburb:string person_id:integer company_id:integer

$ rails g scaffold Person name:string

$ rails g scaffold Company name:string

您的模型代码看起来不错.请注意,Rails更喜欢配置惯例",因此地址模型中的belongs_to :person将通过惯例"告诉Rails在地址表中查找格式为person_id的外键.

Your model code looks good. Note that Rails prefers "convention of configuration" so belongs_to :person in the Address model will, by 'convention', tell rails to look for a foreign key of the form person_id within the Address table.

这篇关于Rails has_one关联混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆