繁体   English   中英

如何进行多个has_one模型关联?

[英]How to do multiple has_one model associations?

我正在尝试在视图中访问用户角色的标题。 我希望能够做到这一点user.user_details.role.title

user.user_details.role给我#错误的undefined method角色

我的协会有什么不对的地方?

class User < ActiveRecord::Base
  has_one :user_details, :dependent => :destroy
  has_one :role, :through => :user_details
end

class UserDetails < ActiveRecord::Base
  belongs_to :user
  has_one :role
end

class Role < ActiveRecord::Base
  belongs_to :user_details
end

您对UserDetails模型的命名错误。 将其更改为UserDetail并在关联中进行更新。

然后,您将可以通过user.user_detail.role访问角色。 因为对于has_one关联,您必须使用单数名称。

class User < ActiveRecord::Base
  has_one :user_detail, :dependent => :destroy
  has_one :role, :through => :user_detail
end

class UserDetail < ActiveRecord::Base
  belongs_to :user
  has_one :role
end

class Role < ActiveRecord::Base
  belongs_to :user_detail
end

暂无
暂无

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

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