I have the follow model setup:
class Favorite < ActiveRecord::Base
belongs_to :favoritable, :polymorphic => true
belongs_to :us开发者_开发技巧er
end
class Photo < ActiveRecord::Base
belongs_to :user
has_many :favorites, :as => :favoritable
end
class User < ActiveRecord::Base
has_many :photos
end
And that Favorite
model has favoritable_id
and favoritable_type` fields.
What I ultimately want to do is check and see if a User
has already marked a photo as a favorite.
I'm able to create the database record without issue...it's the checking to see if that user already has favorited the photo (or other data type) that I'm having issues with.
I could obviously do some sort of raw SQL query to get it, but seems like there's gotta be a more "standard" way of doing it.
I'm running Rails 3.0.3.
you can add two other associations in the User model and a method that checks if the photo is favorite :
has_many :favorites
has_many :favorites_photos, :through => :favorites, :source => :favoritable, :source_type => 'Photo'
def photo_favorite?(photo)
favorites_photos.exists?(photo.id)
end
or more simply just by adding this method to the Photo model :
def favorite_for?(user)
favorites.exists?(:user_id => user.id)
end
I did not tested it, but I think it should work.
精彩评论