本文介绍了多的has_many关系,同一型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,用户可以创建帖子

用户
 的has_many:帖子
帖子
 belongs_to的:用户

不过,我想也让用户的帖子储存为书签。所以我增加了以下内容:

书签
 belongs_to的:交
 belongs_to的:用户
用户
 的has_many:帖子
 的has_many:帖子,:通过=> :书签
帖子
 belongs_to的:用户
 的has_many:帖子,:通过=> :书签

这不可能是正确的,因为它现在是不明确的,当我做@ user.posts。这是否指的是用户写的职位或职位用户书签?

你怎么解决这个问题得到什么呢?

解决方案

通过给你的协会唯一的名称。这并不是说你不能明确地访问它们,那就是你的第二个被摧毁的第一个。

而不是调用的两个职位,使用 bookmarked_posts 你的第二个关联:

的has_many:bookmarked_posts,通过::书签,来源:帖子

I have a model User that can create Posts

User
 has_many :posts
Post
 belongs_to :user

However, I want to also allow users to save posts as bookmarks. So I added the following:

Bookmark
 belongs_to :post
 belongs_to :user
User
 has_many :posts
 has_many :posts, :through => :bookmarks
Post
 belongs_to :user
 has_many :posts, :through => :bookmarks

This can't be right because it is now ambiguous when I do @user.posts . Does that refer to the posts the user wrote or the posts the user bookmarked?

How do you get around this problem?

解决方案

By giving your associations unique names. It's not that you can't unambiguously access them, it's that your second one is destroying the first one.

Instead of calling both posts, use bookmarked_posts for your second association:

has_many :bookmarked_posts, through: :bookmarks, source: :posts

这篇关于多的has_many关系,同一型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:22