我的模型目前低于。
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.social
然后,我还想使用:through
选项直接从User
对象访问Twitter
或Facebook
对象,以调用单个方法,如下所示:
user.socials
因此,我尝试修改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
sample2
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
发布于 2019-01-09 13:12:46
这是个老问题,但我相信它会对某人有帮助的。
我没有找到一个很好的解决方案,但我已经找到了一个简单的解决方案,可能是一个缓慢的解决方案。
您必须知道与您(在您的情况下)身份验证模型关联的所有可能实体。然后您的用户模型应该有一个名为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
希望它能帮到别人!
https://stackoverflow.com/questions/26644080
复制