How do I use multiple source_type?

My models are below at the moment.

user.rb

class User < ActiveRecord::Base
  has_many :authentications
end

      

authentication.rb

class Authentication < ActiveRecord::Base
  belongs_to :user
  belongs_to :social, polymorphic: true 
end

      

facebook.rb

class Facebook < ActiveRecord::Base
  has_one :authentication, as: :social
end

      

twitter.rb

class Twitter < ActiveRecord::Base
  has_one :authentication, as: :social
end

      

Now, thanks to polymorphic association, I can access or from objects like this: Twitter

Facebook

Authentication

 authentication.social

      

Then I want to access the object Twitter

or Facebook

directly from the object User

using a parameter to call one method as shown below: :through

user.socials

      

So, I tried modifying the model User

, for example the following two samples:

sample1

class User < ActiveRecord::Base
  has_many :authentications
  has_many :socials, through: :authentications, source: :social, source_type: "Twitter"
  has_many :socials, through: :authentications, source: :social, source_type: "Facebook"
end

      

sample2

class User < ActiveRecord::Base
  has_many :authentications
  has_many :socials, through: :authentications, source: :social, source_type: ["Twitter", "Facebook"]
end

      

But neither approach worked.

How can I access these objects with a single method, for example user.socials

?

I've heard that and are intended to use polymorphic association on . If we need to use separate methods such as and instead , I think these options are contrary to their original concept. :source

:source_type

:through

user.twitters

user.facebooks

user.socials

Thanks in advance.

: change

I use

ruby 2.1.2p95
Rails 4.2.0.beta2

      

+6


source to share


1 answer


This is an old question, but I believe it will help someone.

I didn't find a good solution, but I found a simple solution that can be slow.

You should be aware of all the possible entities associated with your (in your case) authentication model. Then your user model should have a method named socials

. You should have something like this:



class User < ActiveRecord::Base
  has_many :authentications
  has_many :twitters, through: :authentications, source: :social, source_type: "Twitter"
  has_many :facebooks, through: :authentications, source: :social, source_type: "Facebook"

 def socials
  twitters + facebooks
 end
end

      

Hope this helps someone! : D

0


source







All Articles