繁体   English   中英

ActiveRecord:我是否需要belongs_to和has_one

[英]ActiveRecord: Do I need both belongs_to and has_one

我有2个模型,即useruserprofile 用户和userprofile之间存在一对一的关系

class Userprofile < ActiveRecord::Base
   attr_accessible :fname, :lname, :iswoman, :age, :urlphoto, :user_id

   belongs_to: user

end

class User < ActiveRecord::Base
   attr_accessible :name, :provider, :uid

   has_one: userprofile
end

我想知道我是否需要两个类来设置连接,或者只需要belongs_tohas_one就足够了? 其他方法也是如此,例如has-many

您可以在任何需要的地方定义关联。 如果在某些时候你需要说user.userprofile ,那么在User包含has_one :userprofile 同样,如果您需要说userprofile.user ,那么在Userprofile包含belongs_to user

换句话说,关联是相对的。 您可以指定模型A has_one :b而不指定模型B belongs_to :a 您只需定义所需内容即可。 对于一对多和多对多关联也是如此。

确保已将user_id迁移到“userprofiles”表。

在userprofiles和user之间只有一个belongs_to关系,默认为has_one。 但是,在两个模型上指定关联是明智的(Rails-proper)。

毕竟,如果你想要一个has_many关联(etc),你会想要指定它。

查看http://guides.rubyonrails.org/association_basics.html了解更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM