Rails中"has_one"和"belongs_to"之间的差异

use*_*684 2 ruby-on-rails

有什么不同?的优点和缺点?这对我来说有点混乱.

谢谢.

coo*_*sse 6

当关系为1-1时,将belongs_to放入具有外键的表中,并将has_one放在引用的表中.

当关系为1-n时,将belongs_to放在具有外键的表中,并将has_many放在引用的表中


Mar*_*rce 5

属于使用外键的表.对于以下内容:

class User < ActiveRecord::Base
  has_one :profile
end
class Profile < ActiveRecord::Base
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

profiles表需要有一个user_id字段来引用users表中的记录.

知道哪个属于哪个以及哪个属于has_one是许多人都在努力的事情.通常,如果has_one可能变为has_many,那么那就是需要has_one的那一方.