本文介绍了ActiveRecord的:我两样都需要belongs_to的和HAS_ONE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个型号,分别是用户用户配置文件。有用户和用户配置文件之间的一比一的关系

I have 2 models, namely user and userprofile. There is a one-to-one relationship between user and 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_to的 HAS_ONE 就足够了?同样的情况也适用于其他的方法,如有一对多

I'd like to know whether I need both class to set the connection or having just either belongs_to or has_one is enough? The same is true for the other methods, such as has-many.

推荐答案

您定义的关联,无论你会需要它。如果在某些时候你需要说 user.userprofile ,然后包括 HAS_ONE:USERPROFILE 用户。同样,如果你需要说 userprofile.user ,然后包括 belongs_to的用户 USERPROFILE

You define the association wherever you will need it. If at some point you need to say user.userprofile, then include has_one :userprofile in User. Likewise, if you need to say userprofile.user, then include belongs_to user in Userprofile.

在换句话说,关联是相对的。您可以指定模型中的 HAS_ONE:乙没有指定B型 belongs_to的:一个。您只需确定你所需要的。这同样适用于一对许多和many-to-many关联

In other words, associations are relative. You can specify that model A has_one :b without specifying that model B belongs_to :a. You simply define what you need. The same goes for one-to-many and many-to-many associations.

只是一定要迁移 USER_ID 来了的UserProfiles表。

Just be sure to have migrated user_id to the "userprofiles" table.

这篇关于ActiveRecord的:我两样都需要belongs_to的和HAS_ONE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:45