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. 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,
has_many :pictures, :through => :favorites, :as => :favorite_pictures
You already defined :pictures
and the :as
option is only used for polymorphic associations. Try this instead:
has_many :favorite_pictures, :through => :favorites, :source => :picture
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.