Ric*_*d77 12 activerecord ruby-on-rails
我有2个模型,即user和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
Run Code Online (Sandbox Code Playgroud)
我想知道我是否需要两个类来设置连接,或者只需要belongs_to或has_one就足够了?其他方法也是如此,例如has-many.
cde*_*ers 28
您可以在任何需要的地方定义关联.如果在某些时候你需要说的user.userprofile,然后包括has_one :userprofile在User.同样,如果你需要说的userprofile.user,然后包括belongs_to user在Userprofile.
换句话说,关联是相对的.您可以指定模型中的has_one :b无指定B型belongs_to :a.您只需定义所需内容即可.对于一对多和多对多关联也是如此.
确保已迁移user_id到"userprofiles"表.
| 归档时间: |
|
| 查看次数: |
3533 次 |
| 最近记录: |