我的模型目前低于。
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
现在由于多态关联,我可以访问
Twitter
或 Facebook
来自 Authentication
的对象对象如下: authentication.social
然后我想访问
Twitter
或 Facebook
对象直接来自 User
对象以及使用 :through
调用单个方法的选项,如下所示:user.socials
所以我尝试修改
User
模型如下两个示例:sample 1
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
sample 2
class User < ActiveRecord::Base
has_many :authentications
has_many :socials, through: :authentications, source: :social, source_type: ["Twitter", "Facebook"]
end
但是这两种方法都没有奏效。
如何使用
user.socials
等单一方法访问这些对象?听说
:source
和 :source_type
用于在 上使用多态关联:through
.如果我们必须使用单独的方法,如
user.twitters
和 user.facebooks
而不是 user.socials
,我认为这些选项与其最初的概念相矛盾。提前致谢。
:编辑
我正在使用
ruby 2.1.2p95
Rails 4.2.0.beta2
最佳答案
这是一个老问题,但我相信它会帮助某人。
我没有找到一个很好的解决方案,但我已经找到了一个可能很慢的简单解决方案。
您必须知道与您的(在您的情况下)身份验证模型相关联的所有可能实体。那么你的 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
希望它可以帮助某人! :D
关于ruby-on-rails-4 - 如何使用多个 source_type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26644080/