[英]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.