如何使用多个source_type?

tar*_*rky 9 ruby-on-rails-4

我的模型目前在下面.

user.rb

class User < ActiveRecord::Base
  has_many :authentications
end
Run Code Online (Sandbox Code Playgroud)

authentication.rb

class Authentication < ActiveRecord::Base
  belongs_to :user
  belongs_to :social, polymorphic: true 
end
Run Code Online (Sandbox Code Playgroud)

facebook.rb

class Facebook < ActiveRecord::Base
  has_one :authentication, as: :social
end
Run Code Online (Sandbox Code Playgroud)

twitter.rb

class Twitter < ActiveRecord::Base
  has_one :authentication, as: :social
end
Run Code Online (Sandbox Code Playgroud)

现在感谢多态关联,我可以访问对象中的任何一个TwitterFacebookAuthentication对象,如下所示:

 authentication.social
Run Code Online (Sandbox Code Playgroud)

然后我想直接从对象访问TwitterFacebook对象,User使用:through选项来调用单个方法,如下所示:

user.socials
Run Code Online (Sandbox Code Playgroud)

所以我尝试修改User模型,如下面的两个样本:

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
Run Code Online (Sandbox Code Playgroud)

SAMPLE2

class User < ActiveRecord::Base
  has_many :authentications
  has_many :socials, through: :authentications, source: :social, source_type: ["Twitter", "Facebook"]
end
Run Code Online (Sandbox Code Playgroud)

但两种方法都不奏效.

如何使用单一方法访问这些对象user.socials

我听说过:source并且:source_type正在使用多态关联:through.如果一定要使用不同的方法,如user.twittersuser.facebooks,而不是user.socials,我认为这些选项是矛盾到原来的概念.

提前致谢.

:编辑

我正在使用

ruby 2.1.2p95
Rails 4.2.0.beta2
Run Code Online (Sandbox Code Playgroud)

Fáb*_*újo 5

这是一个老问题,但我相信它会帮助某人。

我没有找到一个很好的解决方案,但我已经找到了一个可能很慢的简单解决方案。

您必须知道与您的(在您的情况下)身份验证模型相关联的所有可能实体。那么你的 User 模型应该有一个名为socials. 你应该有这样的事情:

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
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助某人!:D