Rails 3 中的 Has_and_belongs_to_many
我试图通过 stackoverflow 来纠正我的情况,但不幸的是我让自己彻底困惑了。
我有两个 has_many 到 has_many 关系:用户 has_and_belongs_to_many 角色和角色 has_and_belongs_to_many Pod。我已经设置了正确的表和所有内容(即 role_users 和 pod_roles 表):我知道它至少部分有效,因为我能够执行 @user.roles 并获取该用户的所有角色。
但是,我想更进一步:我希望能够执行类似于 @user.roles.pods 的操作来获取与该用户相关的所有 pod。 @user.roles.pods 不起作用之后:这就是我尝试做的事情:
@current_user_roles = current_user.roles
@pods = Array.new
@current_user_roles.each do |role|
@pods.push(role.pods)
end
@pods.each do |pod|
puts(pod.name+"-----------------")
end
不起作用。这只是为了尝试获得一些超级简单的东西 - 尝试让所有 Pod 的名称显示出来,我可以判断它是否正常工作。
I've tried to look through stackoverflow to remedy my situation but unfortunately I've just made myself thoroughly confused.
I have two has_many to has_many relationships: Users has_and_belongs_to_many Roles, and Roles has_and_belongs_to_many Pods. I've already set up the correct tables and everything (i.e. the role_users and pod_roles tables): I know it's at least partially working because I'm able to do @user.roles and get all of that user's roles.
However, I want to take it one step further: I want to be able to do something akin to @user.roles.pods to get all of the pods pertaining to that user. After @user.roles.pods didn't work: here's what I tried to do:
@current_user_roles = current_user.roles
@pods = Array.new
@current_user_roles.each do |role|
@pods.push(role.pods)
end
@pods.each do |pod|
puts(pod.name+"-----------------")
end
Didn't work. This is just to try to get something super simple -- to try to get all of the pods' names to appear to I can tell if it's working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试以下方法:
Here's something you could try: