在Rails中,使用"has_many with belongs_to"vs"has_many with has_one"有什么区别?

nop*_*ole 5 activerecord ruby-on-rails has-one belongs-to

例如,在

class Student < ActiveRecord::Base
  has_many :awards
end

class Awards < ActiveRecord::Base
  belongs_to :student
end
Run Code Online (Sandbox Code Playgroud)

以上应该是正确的用法,但是如果我们使用的话

class Student < ActiveRecord::Base
  has_many :awards
end

class Awards < ActiveRecord::Base
  has_one :student
end
Run Code Online (Sandbox Code Playgroud)

上面的内容也不能student.awards作为一个奖励对象的数组,award.student作为奖励的接收者的学生对象,所以工作方式与帖子顶部的方法相同吗?

Mis*_*cha 7

has_one 用于一对一关系,而不是一对多关系.

正确使用has_one:

class Student < ActiveRecord::Base
  has_one :id_card
end

class IdCard < ActiveRecord::Base
  belongs_to :student
end
Run Code Online (Sandbox Code Playgroud)

  • 重点是:具有`belongs_to`语句的类是其表模式中具有外键的类. (3认同)