ActiveRecord:我是否需要belongs_to和has_one

我有2个模型,即useruserprofile 。 用户和用户配置文件之间存在一对一的关系

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关联(等),你会想要指定它。

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