ruby-on-rails-4 - 如何使用多个 source_type?

标签 ruby-on-rails-4

我的模型目前低于。

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

现在由于多态关联,我可以访问 TwitterFacebook 来自 Authentication 的对象对象如下:
 authentication.social

然后我想访问TwitterFacebook对象直接来自 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/

相关文章:

ruby-on-rails - StoreController 中的 NoMethodError#display_cart

ruby-on-rails-4 - 升级到 Rails 4.1 后,acts-as-taggable-on 不起作用

ruby-on-rails - rails 4 : display clickable link in mailer view

ruby-on-rails - rails API : Best way to implement authentication?

css - 如何对齐来自 collection_check_boxes 的输入和标签?

css - 为什么保存 .scss 文件会在 Rails 4 中创建一个 .css 文件?

mysql - Rails 使用连接关联提取值

ruby-on-rails - 如何允许用户能够在 Rails 应用程序中上传到我的 google 驱动器,然后在应用程序中为他们提供 google 文档的预览链接?

ruby-on-rails - 将选项传递给 ActiveModel 序列化程序

ruby-on-rails - 使用 AR 纠正 Postgres 和 SQLite3 中以 nil 值排序日期时的不同行为