简体   繁体   English

遇到has_many问题:通过关联

[英]Having trouble with has_many :through association

I finally figured out a way to let a user save favorites through a joined model. 我终于找到了让用户通过连接模型保存收藏夹的方法。 Here's my user model: 这是我的用户模型:

has_many :pictures, :through => :favorites

If I want to get the pictures the user favorited, I can call 如果我想获得用户收藏的图片,我可以打电话

@pictures = user.pictures

Originally, this would show all the user's uploads and not favorites, but I still want to be able to show all their uploads. 最初,这将显示所有用户的上传而不是收藏,但我仍然希望能够显示他们所有上传的内容。 I would like to be able to call @user.pictures for all uploads and @user.favorite_pictures for their favorited. 我希望能够为所有上传调用@ user.pictures,并为他们的收藏调用@ user.favorite_pictures。 I tried this, but it didn't work: 我试过这个,但它不起作用:

has_many :pictures
has_many :favorites
has_many :pictures, :through => :favorites, :as => :favorite_pictures

### @user.favorite_pictures produces an error

Thanks in advance 提前致谢

The error lies in your 3rd line, 错误在于你的第3行,

has_many :pictures, :through => :favorites, :as => :favorite_pictures

You already defined :pictures and the :as option is only used for polymorphic associations. 您已定义:pictures:as选项仅用于多态关联。 Try this instead: 试试这个:

has_many :favorite_pictures, :through => :favorites, :source => :picture

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

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