简体   繁体   English

ActiveRecord:我是否需要belongs_to和has_one

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

I have 2 models, namely user and userprofile . 我有2个模型,即useruserprofile There is a one-to-one relationship between user and userprofile. 用户和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

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? 我想知道我是否需要两个类来设置连接,或者只需要belongs_tohas_one就足够了? The same is true for the other methods, such as has-many . 其他方法也是如此,例如has-many

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 . 如果在某些时候你需要说user.userprofile ,那么在User包含has_one :userprofile Likewise, if you need to say userprofile.user , then include belongs_to user in Userprofile . 同样,如果您需要说userprofile.user ,那么在Userprofile包含belongs_to user

In other words, associations are relative. 换句话说,关联是相对的。 You can specify that model A has_one :b without specifying that model B belongs_to :a . 您可以指定模型A has_one :b而不指定模型B belongs_to :a You simply define what you need. 您只需定义所需内容即可。 The same goes for one-to-many and many-to-many associations. 对于一对多和多对多关联也是如此。

Just be sure to have migrated user_id to the "userprofiles" table. 确保已将user_id迁移到“userprofiles”表。

Having just a belongs_to relationship between userprofiles and user does default to has_one. 在userprofiles和user之间只有一个belongs_to关系,默认为has_one。 However, it would be wise (Rails-proper) to specify the association on both models. 但是,在两个模型上指定关联是明智的(Rails-proper)。

After all, if you wanted a has_many association (etc) you would want to specify that. 毕竟,如果你想要一个has_many关联(etc),你会想要指定它。

Check out http://guides.rubyonrails.org/association_basics.html for more info 查看http://guides.rubyonrails.org/association_basics.html了解更多信息

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

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