What's the difference between belongs_to and has_one?

前端 未结 5 490
有刺的猬
有刺的猬 2020-11-28 02:04

What is the difference between a belongs_to and a has_one?

Reading the Ruby on Rails guide hasn\'t helped me.

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 02:44

    It's about where the foreign key sits.

    class Foo < AR:Base
    end
    
    • If foo belongs_to :bar, then the foos table has a bar_id column
    • If foo has_one :bar, then the bars table has a foo_id column

    On the conceptual level, if your class A has a has_one relationship with class B then class A is the parent of class B hence your class B will have a belongs_to relationship with class A since it is the child of class A.

    Both express a 1-1 relationship. The difference is mostly where to place the foreign key, which goes on the table for the class declaring the belongs_to relationship.

    class User < ActiveRecord::Base
      # I reference an account.
      belongs_to :account
    end
    
    class Account < ActiveRecord::Base
      # One user references me.
      has_one :user
    end
    

    The tables for these classes could look something like:

    CREATE TABLE users (
      id int(11) NOT NULL auto_increment,
      account_id int(11) default NULL,
      name varchar default NULL,
      PRIMARY KEY  (id)
    )
    
    CREATE TABLE accounts (
      id int(11) NOT NULL auto_increment,
      name varchar default NULL,
      PRIMARY KEY  (id)
    )
    

提交回复
热议问题