Rails has_one combines confusion

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 have 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'm missing something. Is an address needed for polymorphic association?

I'm pretty lost, so any guidance would be appreciated.

Greetings

+1
source share
1 answer

You are missing foreign keys and / or have them in the wrong place. Remember that in the "child" model, a foreign key is required. This is the model that is. Thus, the address of Person has_one, the address is obsessed and must contain a foreign key that refers to Person.

- , . , , belongs_to a Person :

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

, .

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

:

$ 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 "" "" person_id Address.

+2

Source: https://habr.com/ru/post/1694992/


All Articles