paulus
paulus

Reputation: 655

ROR: Check object inclusion in polymorphic association

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!

Upvotes: 1

Views: 133

Answers (1)

aNoble
aNoble

Reputation: 7072

It looks like your problems lies right here

has_many :languages, :class_name => 'UserLanguage', :as => :speakable

Because you set class_name to UserLanguage, u.languages is giving you a set of UserLanguage objects not Language objects.

If you change your user.rb associations, as below, u.languages should give you what you're looking for.

has_many :user_languages, :as => :speakable
has_many :languages, :through => :user_languages

Upvotes: 2

Related Questions