Rails has_one association confusion

烈酒焚心 提交于 2019-12-11 02:48:03

问题


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.

Cheers


回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/22318716/rails-has-one-association-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!