I’m looking for a way to check if certain object is included in polymorphic association.
My example is
language.rb (this is essentially a list of available languages)
has_many :user_languages
user_language.rb
belongs_to :language
belongs_to :speakable, :polymorphic => true
user.rb
has_many :languages, :class_name => 'UserLanguage', :as => :speakable
Now i want to check is user has certain language. The idea I had is to use include? method in a form of
u = User.find(1)
l = Language.find(1)
u.languages.include?(l)
but it always returns false although u.languages gives
#<UserLanguage id: 1, language_id: 1, speakable_id: 1, speakable_type: "User">
What would be the proper way to arrange this check?
Thank you!
It looks like your problems lies right here
Because you set
class_nametoUserLanguage,u.languagesis giving you a set ofUserLanguageobjects notLanguageobjects.If you change your
user.rbassociations, as below,u.languagesshould give you what you’re looking for.