[英]How to do multiple has_one model associations?
I'm trying to access the title of a user's role in a view. 我正在尝试在视图中访问用户角色的标题。 I want to be able to do this
user.user_details.role.title
. 我希望能够做到这一点
user.user_details.role.title
。
user.user_details.role
gives me the error undefined method
role' for #` user.user_details.role
给我#错误的undefined method
角色
What's wrong with my associations that this is not working? 我的协会有什么不对的地方?
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
Your naming for UserDetails
model is wrong. 您对
UserDetails
模型的命名错误。 Change it to UserDetail
& also update in the association. 将其更改为
UserDetail
并在关联中进行更新。
Then you will be able to access the role by user.user_detail.role
. 然后,您将可以通过
user.user_detail.role
访问角色。 Because for has_one
association you have to use singular names. 因为对于
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.